Georgy
Georgy

Reputation: 2462

How to erase table data in Django?

I 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.

Upvotes: 2

Views: 2391

Answers (3)

Aaron Williams
Aaron Williams

Reputation: 643

I also needed a way to clear particular tables before using loaddata to backport data to test environments. This works for a particular table:

echo "delete from my_table" | python manage.py dbshell

Upvotes: 0

doru
doru

Reputation: 9110

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.

Upvotes: 0

Sayse
Sayse

Reputation: 43300

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

Upvotes: 2

Related Questions