What is unique_together in Django: Definition and Usage
unique_together in Django is a model option that ensures a combination of two or more fields must be unique across all records in the database. It prevents duplicate entries where the specified fields have the same values together.How It Works
Imagine you have a guest list for a party, and you want to make sure no two guests have the same first and last name combination. unique_together works like a rule that checks this before adding a new guest. It looks at the specified fields together and stops duplicates from sneaking in.
In Django, this is set inside a model's Meta class as a tuple of field names. When you save a record, Django checks the database to see if any existing record has the same values for those fields. If yes, it raises an error, so you can't save the duplicate.
This helps keep your data clean and consistent, especially when a single field alone isn't enough to identify a unique record.
Example
This example shows a Django model for a Book where the combination of title and author must be unique. This means you can't have two books with the same title by the same author.
from django.db import models class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100) class Meta: unique_together = (('title', 'author'),) def __str__(self): return f"{self.title} by {self.author}"
When to Use
Use unique_together when you want to ensure that a combination of fields is unique, but each field alone can have duplicates. For example:
- In a user address book, the combination of
userandphone_numbershould be unique to avoid duplicate phone numbers for the same user. - In an event registration system, the pair of
eventandattendeeshould be unique to prevent double registration. - In a product catalog, the combination of
product_codeandwarehouse_locationmight need to be unique to track stock correctly.
This helps maintain data integrity where uniqueness depends on multiple fields working together.
Key Points
unique_togetheris defined inside a model'sMetaclass as a tuple of tuples of field names.- It enforces uniqueness on the combination of specified fields, not on individual fields.
- Trying to save duplicate combinations raises an error, preventing bad data.
- It is useful when no single field uniquely identifies a record but a group of fields does.
- In Django 2.2+,
UniqueConstraintwithconstraintsis the modern alternative, butunique_togetheris still widely used.
Key Takeaways
unique_together ensures a unique combination of fields in Django models.Meta class as a tuple of field names.UniqueConstraint as a more flexible alternative.