小编Joh*_*hao的帖子

有没有更优雅的方法在 Django 模型中添加值敏感的唯一一起约束?

问题是这样的:

我有一个这样的模型:

class UserBook(models.Model):
    user = models.ForeignKey(User)
    book = models.ForeignKey(Book)
    is_active = models.BooleanField(default=False)

    class Meta:
        unique_together = ("user", "book")
Run Code Online (Sandbox Code Playgroud)

显然,这个模型已经对现场用户书籍有了独特的共同约束。数据库中可能会有一些这样的条目:

    ------------------------------
    |user_id  book_id  is_active |
    |      1        1          0 |
    |      1        2          0 |
    |      1        3          1 |
    ------------------------------
Run Code Online (Sandbox Code Playgroud)

我还要添加一个约束,即每个用户最多可以拥有一个is_active字段值为 1(True) 的条目。

目前我通过将模型更改为这样来解决这个问题:

class UserBook(models.Model):
    user = models.ForeignKey(User)
    book = models.ForeignKey(Book)
    is_active = models.BooleanField(default=False)
    key = models.charFeild(max_length=255, unique=True)

    class Meta:
        unique_together = ("user", "book")

    def save(self, *args, **kwargs):
        if self.is_active:
            self.key = "%s_%s" …
Run Code Online (Sandbox Code Playgroud)

python django django-models django-database

4
推荐指数
3
解决办法
1937
查看次数

标签 统计

django ×1

django-database ×1

django-models ×1

python ×1