eugene
eugene

Reputation: 41715

constraint in Django: exactly 1 of 2 foreign keys has to be null

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.

Upvotes: 5

Views: 1403

Answers (2)

Kiran Karandikar
Kiran Karandikar

Reputation: 1

You can use the following method :

Class TestModel(models.Model):
   forgein_key_1 = models.ForeignKey(YourModel)
   forgein_key_2 = models.ForeignKey(YourOtherModel) 

and override the save method as:

    def save(self, *args, **kargs):
        if not (self.forgein_key_1 or self.forgein_key_2):
          raise Exception("Your Custom Exception Message here")
        super(self, TestModel).save(*args, **kargs)

Upvotes: 0

Akshar Raaj
Akshar Raaj

Reputation: 15221

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)

Upvotes: 5

Related Questions