Django: Enforce multiple field uniqueness on models

Django just keeps getting better and better.

I thought there would be hell to pay with admin form save overriding but it was surprisingly easy.

In the model you wish to enforce uniqueness, simply add a Meta class declaration and give it the property "unique_together".

class SomeModel(models.Model):
class Meta:
unique_together = (("fieldA", "fieldB"),)

fieldA = models.ForeignKey(BlahA)
fieldB = models.ForeignKey(BlahB)

description = models.TextField()

Whalla! Now it will not let you add any rows which would break the "fieldA AND fieldB" uniqueness constraint.

The change is made at a database level so if data already exists you'll have to migrate the changes somehow.

[ Source ]

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog