简体   繁体   English

如何擦除Django中的表数据?

[英]How to erase table data in Django?

I wrote a simple script for populating the table created with Django models.我编写了一个简单的脚本来填充用 Django 模型创建的表。 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() .我想删除这些数据并重新开始填充,但如果我只使用Model.objects.all().delete() ,它看起来像表存储以前的主键(因此新对象不会从pk=1开始Model.objects.all().delete() .

How can I erase all the previous data without DROP TABLE ?如何在没有DROP TABLE情况下擦除所有以前的数据? If DROP is the most convenient way, is this Django : Table doesn't exist solution for restoring is the only one?如果DROP是最方便的方法,那么这个Django : Table does not exist恢复的解决方案是唯一的吗?

The desired functionality is erasing data before every script run, automatically.所需的功能是在每个脚本运行之前自动擦除数据。 Thank you in advance.先感谢您。

You can just use flush你可以只使用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通过manage.py flush调用

Are there any ways to use flush just for the set of tables, not database?有什么方法可以只对一组表而不是数据库使用flush吗?

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. Flush 有一个选项来指定您要刷新的数据库( -database ),但您不能指定某些表,因为这可能会破坏表之间的关系,从而使数据无效。

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如果您真的需要这样做,您当然可以创建自己的命令,该命令只会遍历表并删除对象,但这当然不会执行flush 所做post-synchronization步骤

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.有一种方法可以只删除给定 django 应用程序的表而不是整个数据库:您可以使用sqlclear并将其通过管道传输到dbshell管理命令。

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. 在这里查看更多信息。

I also needed a way to clear particular tables before using loaddata to backport data to test environments.在使用 loaddata 将数据反向移植到测试环境之前,我还需要一种清除特定表的方法。 This works for a particular table:这适用于特定表:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM