Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django polymorphic models with unique_together

Lets say I have these this base model:

class Trackable(PolymorphicModel):
    uuid = UUIDField(unique=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

And a child model extends it:

class Like(Trackable):
    content = models.ForeignKey(Content, related_name='likes')

    class Meta:
        unique_together = ['content', 'created_by']

When I run migration, it complains about:

django.db.models.fields.FieldDoesNotExist: Like has no field named u'created_by'
like image 230
James Lin Avatar asked Mar 01 '15 22:03

James Lin


1 Answers

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.

like image 138
jcdude Avatar answered Oct 23 '22 13:10

jcdude