Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify uniqueness for a tuple of field in a Django model

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?

like image 787
Ber Avatar asked Jan 23 '09 09:01

Ber


People also ask

How do you make two fields unique in Django?

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.

What is unique constraint in Django?

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.

How do you define choice fields in Django?

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.


1 Answers

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.

like image 121
Baishampayan Ghose Avatar answered Sep 23 '22 19:09

Baishampayan Ghose