Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
652 views
in Technique[技术] by (71.8m points)

mysql - How do I create a Django model with ForeignKeys which does not cascade deletes to its children?

One of my models which has ForeignKey's is actually a MySQL view on other tables. The problem I'm running into is that when I delete data from these tables, Django, as described in the "deleting objects" documentation...

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.

...tries to remove rows from my view, which of course it can't, and so throws the error:

mysql_exceptions.OperationalError '>=(1395, "Can not delete from join view 'my_db.my_mysql_view'"'

Is there any way to specify a ForeignKey constraint on a model which will provide me with all the Django wizardry, but will not cascade deletes onto it? Or, is there a way to ask MySQL to ignore the commands to delete a row from my view instead of raising an error?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Django 1.3a1 and up support this via ForeignKey's on_delete argument.

The following example sets the field NULL upon deletion of the foreign key. See the documentation for more options.

user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...