How to erase table data in Django?

I did wrote a simple script for populating the table created with Django models. I did make mistakes during the development process and have corrupted data in my table (it is accessible but has wrong images, names, urls). I want to erase this data and start the populating over, but it looks like the table stores previous primary keys (so the new objects do not start from pk=1) if I just use Model.objects.all().delete().

How can I erase all the previous data without DROP TABLE? If DROP is the most convenient way, is this Django : Table doesn't exist solution for restoring is the only one?

The desired functionality is erasing data before every script run, automatically. Thank you in advance.

Answers


You can just use flush

Removes all data from the database and re-executes any post-synchronization handlers. The table of which migrations have been applied is not cleared.

Called via manage.py flush

Are there any ways to use flush just for the set of tables, not database?

No, not really. Flush has an option to specify what database you're flushing (-database) but you can't specify certain tables since that has the possibility of breaking relationships between tables which would invalidate data.

If you really need to do this, you could of course make your own command that will just go through the tables and delete the objects but this of course won't do the post-synchronization steps that flush does


There is a way to drop only the tables of a given django app and not the whole database: you can use sqlclear and pipe it to dbshell management command.

python manage.py sqlclear app_name | python manage.py dbshell

The command can be applied only if the app has no migrations. See here more info.


Need Your Help

Adding a web address to a <a href="value">

php html email

I have an upload script that write a index.html file, I modified it to mail me the results, however the point to the root, since the email isn't in the root, the image doesn't load.

QTableWidget functions in a QTabWidget

c++ qt containers qt5.1

How can I select a QTableWidget cell in a QTabWidget tab?