I would like to delete an instance of the model, but only if it does not have another instance of another class with a foreign key pointing to it. From the Django documentation:
When Django deletes an object, it emulates the behavior of the SQL ON DELETE CASCADE constraint — in other words, any objects that have foreign keys pointing to the deleted object will be deleted along with it.
In this example:
class TestA(models.Model)
name = models.CharField()
class TestB(models.Model)
name = models.CharField()
TestAs = models.ManyToManyField(TestA)
I would like something like:
tA = TestA(name="testA1")
tB = TestB(name="testB1")
tB.testAs.add(tA)
t = TestA.objects.get(name="testA1")
if is_not_foreignkey(t):
t.delete()
else:
print "Error, some instance is using this"
Must print an error. I know that I can check specific instances that install sets of foreign keys, for example, in this case check t.TestB_set (), but I'm looking for a more general solution for any given model.