43

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?

4 Answers 4

76

Just add unique=True in the field, so:

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

Refer docs for more information.

4
  • How to do this so it doesn't work with Dog and dog? So if I write one with the name dog, then Dog will not work next time, or DoG doG dOg will not work either, how can I do this? Commented Aug 28, 2021 at 4:47
  • 1
    this is an old answer, but probably you would want to convert all yours entries to lower case Commented Sep 1, 2021 at 16:25
  • I found the solution for this, but forgot were I found it. capitalizeFirtChar = lambda s: s[:1].upper() + s[1:] def save(self, force_insert=False, force_update=False): self.name = self.name.lower() self.name = capitalizeFirtChar(self.name) # If the name already exists if not Category.objects.filter(name__iexact=self.name).exists(): super(Category, self).save(force_insert, force_update) Commented Sep 2, 2021 at 6:26
  • very careful with that pre-hook, probably you're adding more queries to your lookup an thuis making slower request Commented Sep 2, 2021 at 17:13
9

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
6

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

1

If you are looking for a unique case insensitive, then do this.

example "my NamE is John" and "MY naME is jOHN" should match and will not work to have 2,

because if you write "my NamE is John" it will become "My name is john".

and "MY naME is jOHN" will also become "My name is john".


models.py

1. add this code to the top.

capitalizeFirstChar = lambda s: s[:1].upper() + s[1:]

2. Then here is an example how to use it.

    class MyModel(models.Model):
        name = models.CharField(max_length=255, unique=True)
    
        def __str__(self):
            return self.name
    
# The save method to convert your text "MY naME is jOHN" to "My name is john"

        def save(self, force_insert=False, force_update=False):
            self.name = self.name.lower()
            self.name = capitalizeFirstChar(self.name)
    
            # If the name already exists
            if not Category.objects.filter(name__iexact=self.name).exists():
                super(Category, self).save(force_insert, force_update)

This solution sucks if you don't want the characters to change in capitalisation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.