开发者

Django: Constraint on multiple model fields

开发者 https://www.devze.com 2023-03-05 12:34 出处:网络
Example: 开发者_运维知识库 class Author(models.Model): first_name = models.CharField() last_name = models.CharField()

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?


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.


unique_together

unique_together = ("first_name", "last_name")

0

精彩评论

暂无评论...
验证码 换一张
取 消