3

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's the recommended way of putting a unique constaint on the full_name? Was thinking of overwriting save but maybe there are better solutions?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Pickels
  • 33,902
  • 26
  • 118
  • 178
  • similar: http://stackoverflow.com/questions/2201598/django-how-to-define-two-fields-unique-as-couple – manji May 13 '11 at 15:08

2 Answers2

4

Take a look at the Meta class option unique_together

You could do it this way:

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 enforced at the DB level with the proper UNIQUE SQL statements.

Lou Franco
  • 87,846
  • 14
  • 132
  • 192
  • It is probably the solution required, but there are edge cases that this won't pick up as a conflict: "'bob' 'brown smith'" and "'bob brown' 'smith'". Full name is the same, but last_name and first_name are different. – Matthew Schinckel May 15 '11 at 09:59
2

unique_together

unique_together = ("first_name", "last_name")

JamesO
  • 25,178
  • 4
  • 40
  • 42