How to Make a Database Table Field Unique in Django


In this article, we show how to make a database table unique in Django.

What this means is for a given field in a database table, only one row can have a specific value. If, for example, if we create a database table of Books and make the title field unique, there cannot be the same title anywhere in the database. Each title has to be unique, so making a field unique, when warranted, is very useful for many real-world database applications.

Of course, you should have an id tag, which is always unique, because it's a primary key. However, certain fields may also need to be unique, because certain fields may need to be unique without any repetition.

So, to make a field unique in Django is very basic. You just set the unique attribute to true.

This is shown in the following code below.

So, in our code we import models from django.db

We then create our database table, Book.

We create a database field called title and make it of type CharField with a max_length of 300 and we set the unique attribute equal to True.

What this does is every title has to be unique, distinct. There cannot be 2 titles in the database table with the same exact title. If you attempt to duplicate a title, the query won't go through and be placed in the database.

And this is just simply how to make a database table field unique in Django.

Related Resources

How to Randomly Select From or Shuffle a List in Python

HTML Comment Box is loading comments...