5

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.

Sergey Orshanskiy
  • 6,794
  • 1
  • 46
  • 50
eugene
  • 39,839
  • 68
  • 255
  • 489
  • Somewhat related: https://stackoverflow.com/questions/6928692/how-to-express-a-one-to-many-relationship-in-django – Sergey Orshanskiy Nov 11 '18 at 21:16
  • This is frequently a design anti-pattern for subtyping. [How can you represent inheritance in a database?](https://stackoverflow.com/q/3579079/3404097) – philipxy Nov 11 '18 at 21:23

2 Answers2

5

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)
Akshar Raaj
  • 14,231
  • 7
  • 51
  • 45
0

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)