Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set the field unique in django?

I have a model class:

class PysicalServer(models.Model):

    serial_number = models.CharField(max_length=64)  # I want to add the unique
    name = models.CharField(max_length=16)

I know use the primary_key can set unique, but the serial_number is not my id field, I can not use the primary_key, is there other property I can set field unique?

like image 403
user7693832 Avatar asked Oct 18 '17 02:10

user7693832


People also ask

How do you create a unique field in Django?

If the verbose name isn't given, Django will automatically create it using the field's attribute name, converting underscores to spaces. A list of validators to run for this field. See the validators documentation for more information. If True, this field must be unique throughout the table.

How does Django get unique data?

One way to get the list of distinct column names from the database is to use distinct() in conjunction with values() .

What is unique constraint in Django?

New in Django 4.0. Positional argument *expressions allows creating functional unique constraints on expressions and database functions. creates a unique constraint on the lowercased value of the name field in descending order and the category field in the default ascending order.


3 Answers

Just add unique=True in the field, so:

serial_number = models.CharField(max_length=64, unique=True)

Refer docs for more information.

like image 188
Mauricio Cortazar Avatar answered Oct 12 '22 15:10

Mauricio Cortazar


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

http://www.learningaboutelectronics.com/Articles/How-to-make-a-database-table-field-unique-in-Django.php

like image 31
Chris Goddy Chinedozie Avatar answered Oct 12 '22 15:10

Chris Goddy Chinedozie


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
like image 36
Eyong Kevin Enowanyo Avatar answered Oct 12 '22 17:10

Eyong Kevin Enowanyo