Menu

Create Unique Together for Two Fields in Django Model: UniqueConstraint

In Django, ensuring data integrity is essential to maintain the consistency and accuracy of your database. One common requirement is to enforce uniqueness for combinations of two or more fields in a model. While the unique_together option within Meta class is a common way to achieve this, Django 2.2 and later versions offer a more explicit approach using the UniqueConstraint option. In this blog post, will explore how to create unique constraint for two fields in Django models using UniqueConstraint .

Imagine you have a Django model representing a user profile, and you want to ensure that each user has unique combination of both their username and email address. In other words, no two users should share the same username and email. Let’s walk through the steps to achieve this using UniqueConstraint .

Step 1: Define Your Model

First, define your model in Django. Here an example of a simple user profile model:

from django.db import models
class UserProfile(models.Model):
    username = models.CharField(max_length=50)
    email = models.EmailField()
    # Other fields...

Step 2: Adding UniqueConstraint

To ensure the uniqueness of both the username and email fields, you can use the UniqueConstraint option within the model Meta class. Modify your model as follows:

from django.db import models
class UserProfile(models.Model):
    username = models.CharField(max_length=50)
    email = models.EmailField()
    class Meta: