How to Make Fields of a Database Table Unique Together in Django


In this article, we show how to make fields of a database table (model) unique together in Django.

So, first of all, what does this mean?

This means that, for a given database table, there cannot be multiple rows of the same data for the fields that are unique together.

Let's go over an example of this.

Let's say we have a website in which a user can create posts. Let's say that this website only permits a user to create a post with a unique title.

In our database table (our model), this means that the author (which is the user) and the title must be unique together. In other words, that same user cannot create a post with another with a title previously used. So this is why we make the author and title fields unique together.

Another person can come along and create a post with that title, but that same user cannot. This makes sense, because this can create spam, and there's really no reason why a user should create posts with identical titles.

So, in Django, we can do this pretty easily, because Django has built-in functionality to make fields of a model unique together.

This can be done by simply adding a class Meta underneath the model.

This is shown in the code below.

So, as you can see, the above code is very simple.

We have a model named Post.

This Post model has 3 fields: user, title, and date.

We want the user and the title to be unique together. In other words, a user cannot create two posts with the same title. Therefore, we make the user and the title fields unique together.

To make fields unique together, we create a class Meta. In this class, we specify the keyword, unique_together, and then create a tuple consisting of all the fields that we want unique together. In this case, we just want 2 fields unique together, but you can specify as many as you want, as long as it's 2 or greater.

And this is how you can make fields of a database table (model) unique together in Django.

Related Resources

How to Randomly Select From or Shuffle a List in Python

HTML Comment Box is loading comments...