[Answer]-Django: Foreign key optional but unique?

1đź‘Ť

Maybe there is a better solution out there, but you could do the following:

  1. create a new attribute d and find a generic way to combine b_id and c_id (e.g. str(b_id) + "*" + str(c_id) and do this automatically on model creation (the signals mechanism might come in handy, here)
  2. use d as primary_key

This is more a work around then a solution, but it should do the trick.

One more thought: Would it be an option to check whether there is aready an existing instance with “Null”/”Null” on creation / update of your instance? This would not solve your problem on database level, but the logics would work as expected.

👤OBu

1đź‘Ť

It’s not a problem with Django but with the SQL spec itself – NULL is not a value, so it must NOT be taken into account for uniqueness constraints checks.

You can either have a “pseudo-null” B record and a “pseudo-null” C record in your db and make them the defaults (and not allow NULL of course), or have a denormalized field like OBu suggests.

-1đź‘Ť

You can use the Unique constraint for b_id column. It wont allow the duplicate entries. Even for a_id column, primary key can be used. Primary key means the combination of unique key and not null constraints.

👤Nagarajan

Leave a comment