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.
Django unique_together is used to make two or more model fields to be unique.
Django automatically creates an index for all models. ForeignKey columns.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With