[Fixed]-Django polymorphic models with unique_together

6👍

Here is how I handled this problem. Bear in mind that I use PostGres as my database and I do not know if the same problems occur with other databases (though I guess that they do).

Unique together constraints can only be applied to a single table or view in PostGres. This means that out of the box Django/Django-polymorphic cannot express database-enforced unique constraints on a combination of fields that are in both a parent table and a child table of Django models in an inheritance hierarchy.

If you really want database enforced unique constraints on these fields, you can do one of these two things:

  1. copy any parent-model fields that are involved in the unique constraint into the child’s table, and express the unique constraint on the child’s fields and the fields copied from the parent, or
  2. create a view on the child that includes both the fields from the parent and those from the child, and express the unique constraint on this view.

You will have to either do this manually, or develop your own framework for inserting/altering/deleting these constraints automatically.

👤jcdude

Leave a comment