[Answer]-Do not delete if there is a FK dependency to obj

1👍

You can use the exists() command in your query.

if main_catalog.objects.filter(catalog__id=pk).exists():
    pass
else:
    Catalog.objects.filter(pk=pk).delete()

0👍

First of all, use a get() with a foreign key, as you only expect one object to be returned. 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()

Leave a comment