close

How can I set the field unique in django?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How can I set the field unique in django in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How can I set the field unique in django?

  1. How can I set the field unique in django?

    As mentioned by the other stackoverflowers above, you can use unique=True. but mind you that this won't work if you want to set a joined unique constraint.

  2. set the field unique in django

    As mentioned by the other stackoverflowers above, you can use unique=True. but mind you that this won't work if you want to set a joined unique constraint.

Method 1

The key word unique=True makes the title CharField unique.

class Book(models.Model):
    title= models.CharField(max_length=300, unique=True)

    def __str__(self):
        return self.title

Method 2

As mentioned by the other stackoverflowers above, you can use unique=True. but mind you that this won’t work if you want to set a joined unique constraint. For example, if you want a combination of fields to be unique, then you should use models.UniqueConstraint as seen below

class Book(models.Model):
    title = models.CharField(max_length=300)
    sub_title = models.CharField(max_length=300)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['title', 'sub_title'], name="%(app_label)s_%(class)s_unique")
        ]

    def __str__(self):
        return self.title

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read