Skip to content

Fix handling of null values in unique_together

Adam Alton requested to merge ignore-null-in-unique-together into master

In "normal" Django (i.e. Postgres), if you have a unique_together constraint and you add a model instance in which the value of any of the fields in the constraint is None, the constraint will be ignored for that instance. In other words, for a three-field constraint, you can have multiple objects where the first two fields are the same and the third field is None.

Strictly speaking this could vary by DB, as the Django ORM sets the unique_together constraint at the DB level. But for Postgres it definitely works this way: https://www.postgresql.org/docs/13/ddl-constraints.html#DDL-CONSTRAINTS-UNIQUE-CONSTRAINTS

And this way makes sense, because, as in the three-field example I've just mentioned, if you wanted to still prevent multiple objects in which only the first two fields are the same then you would just add another tuple to the unique_together constraints for just the first two fields.

Doing it this way is the only way that makes sense.

This PR fixes the gcloudc behaviour to match this.

Merge request reports