开发者

How do I delete in Django? (mysql transactions)

If you are familiar with Django, you know that they have a Authentication system with User model. Of course, I have many other tables that have a Foreign Key to this User model.

If I want to delete this user, how do I architect开发者_运维问答 a script (or through mysql itself) to delete every table that is related to this user?

My only worry is that I can do this manually...but if I add a table , but I forget to add that table to my DELETE operation...then I have a row that links to a deleted, non-existing User.


As far as I understand it, django does an "on delete cascade" by default: http://docs.djangoproject.com/en/dev/topics/db/queries/#deleting-objects


You don't need a script for this. When you delete a record, Django will automatically delete all dependent records (thus taking care of its own database integrity).

This is simple to test. In the admin, go to delete a User. On the confirmation page, you'll see a list of all dependent records in the system. You can use this any time as a quick test to see what's dependent on what (as long as you don't actually click Confirm).

If you perform deletions from your view code with .delete(), all dependent objects will be deleted automatically with no option for confirmation.

From the docs:

When Django deletes an object, it emulates the behavior of the SQL constraint ON DELETE CASCADE -- in other words, any objects which had foreign keys pointing at the object to be deleted will be deleted along with it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜