Leopd Leopd - 4 months ago 41x
Python Question

Django ForeignKey which does not require referential integrity?

I'd like to set up a

field in a django model which points to another table some of the time. But I want it to be okay to insert an id into this field which refers to an entry in the other table which might not be there. So if the row exists in the other table, I'd like to get all the benefits of the ForeignKey relationship. But if not, I'd like this treated as just a number.

Is this possible? Is this what Generic relations are for?


This question was asked a long time ago, but for newcomers there is now a built in way to handle this by setting db_constraint=False on your ForeignKey:


customer = models.ForeignKey('Customer', db_constraint=False)

or if you want to to be nullable as well as not enforcing referential integrity:

customer = models.ForeignKey('Customer', null=True, blank=True, db_constraint=False) 

We use this in cases where we cannot guarantee that the relations will get created in the right order.

EDIT: update link