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?
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.
One way to get the list of distinct column names from the database is to use distinct() in conjunction with values() .
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.
Just add unique=True
in the field, so:
serial_number = models.CharField(max_length=64, unique=True)
Refer docs for more information.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With