Is there a way to specify a Model in Django such that is ensures that pair of fields in unique in the table, in a way similar to the "unique=True" attribute for similar field?
Or do I need to check this constraint in the clean() method?
Using the constraints features UniqueConstraint is preferred over unique_together. From the Django documentation for unique_together : Use UniqueConstraint with the constraints option instead. UniqueConstraint provides more functionality than unique_together.
New in Django 4.0. Positional argument *expressions allows creating functional unique constraints on expressions and database functions. creates a unique constraint on the lowercased value of the name field in descending order and the category field in the default ascending order.
Choices can be any sequence object – not necessarily a list or tuple. The first element in each tuple is the actual value to be set on the model, and the second element is the human-readable name. Let us create a choices field with above semester in our django project named geeksforgeeks.
There is a META option called unique_together
. For example:
class MyModel(models.Model):
field1 = models.BlahField()
field2 = models.FooField()
field3 = models.BazField()
class Meta:
unique_together = ("field1", "field2")
More info on the Django documentation page.
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