[英]Do not delete if there is a FK dependency to obj
I want to do a DELETE
operation for an item in django, but only if there are no FK dependencies. 我想对Django中的项目执行
DELETE
操作,但前提是没有FK依赖项。 I would normally do this: 我通常会这样做:
Catalog.objects.filter(pk=pk).delete()
Which would delete the item and then delete/nullify any dependencies to this particular Catalog object. 它将删除该项目,然后删除/取消对此特定Catalog对象的任何依赖关系。 However, I do not want to delete the item if there are any dependencies.
但是,如果有任何依赖性,我不想删除该项目。 How would I do that in django?
我将如何在django中做到这一点? I was thinking -
我刚在想 -
list(Catalog objects.raw('DELETE FROM main_catalog WHERE pk=%s', pk))
You can use the exists() command in your query. 您可以在查询中使用exist()命令。
if main_catalog.objects.filter(catalog__id=pk).exists():
pass
else:
Catalog.objects.filter(pk=pk).delete()
First of all, use a get() with a foreign key, as you only expect one object to be returned. 首先,将get()与外键一起使用,因为您只希望返回一个对象。 Then check for foreign keys on that object.
然后检查该对象上的外键。
catalog = Catalog.objects.get(pk=pk)
if catalog.foreign_key_1 or catalog.foreign_key_2 : # repeat or's with all fk's on the object
pass
else :
catalog.delete()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.