Django: restriction on several model fields

Example:

class Author(models.Model):
    first_name = models.CharField()
    last_name = models.CharField()

    def _get_full_name(self):
       return '{0} {1}'.format(self.first_name, self.last_name)

   full_name = property(_get_full_name)

What is the recommended way to put a unique constaint in full_name? Thought about rewriting, but maybe there are better solutions?

+3
source share
2 answers

Take a look at the Meta unique_together class option

You can do it as follows:

class Author(models.Model):
    first_name = models.CharField()
    last_name = models.CharField()

    def _get_full_name(self):
       return '{0} {1}'.format(self.first_name, self.last_name)

    full_name = property(_get_full_name)

    class Meta: 
       unique_together = ("first_name", "last_name")

The advantage is that this is provided at the database level with the correct UNIQUE SQL statements.

+4
source

unique_together

unique_together = ("first_name", "last_name")

+2
source

All Articles