constraint in Django: exactly 1 of 2 foreign keys has to be null
constraints, django, foreign-keys
Solution
You can't achive this by adding something on model fields. You will have to put this logic in your `save()`.
class MyModel(models.Model):
fk1 = models.ForeignKey(Some, null=True)
fk2 = models.ForeignKey(Other, null=True)
def save(self, *args, **kwargs):
if not fk1 and not fk2:
raise Exception("You can't leave both fields as null")
super(self, MyModel).save(*args, **kwargs)
Problem
I'd like to allow null on two foreign key fields. But the two fields should not be null at the same time. Actually, exactly one has to be set at any time. How can I express this? The two tables the foreign keys reference are not the same.