Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Constraint on multiple model fields

Tags:

python

django

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?

like image 796
Pickels Avatar asked Jul 25 '26 22:07

Pickels


2 Answers

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.

like image 136
Lou Franco Avatar answered Jul 28 '26 16:07

Lou Franco


unique_together

unique_together = ("first_name", "last_name")

like image 40
JamesO Avatar answered Jul 28 '26 15:07

JamesO



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!