Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Unique Together (with foreign keys)

I have a situation where I want to use the Meta options of unique_together to enforce a certain rule, here's the intermediary model:

class UserProfileExtension(models.Model):     extension = models.ForeignKey(Extension, unique=False)     userprofile = models.ForeignKey(UserProfile, unique=False)     user = models.ForeignKey(User, unique=False)        class Meta:         unique_together = (("userprofile", "extension"),                            ("user", "extension"),                            # How can I enforce UserProfile's Client                             # and Extension to be unique? This obviously                            # doesn't work, but is this idea possible without                            # creating another FK in my intermediary model                             ("userprofile__client", "extension")) 

and here's UserProfile:

class UserProfile(models.Model):     user = models.ForeignKey(User, unique=True)     client = models.ForeignKey(Client) 

Thanks.

like image 982
chiurox Avatar asked Dec 14 '10 14:12

chiurox


People also ask

What is Django unique together?

Django unique_together is used to make two or more model fields to be unique.

Does Django index foreign keys?

Django automatically creates an index for all models. ForeignKey columns.


1 Answers

You can't.

The unique_together clause is directly translated to the SQL unique index. And you can only set those on columns of a single table, not a combination of several tables.

You can add validation for it yourself though, simply overwrite the validate_unique method and add this validation to it.

Docs: http://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.validate_unique

like image 162
Wolph Avatar answered Oct 23 '22 12:10

Wolph