【问题标题】:Is there any more elegant way to add a value sensitive unique together constraint in Django Model?有没有更优雅的方法可以在 Django 模型中添加对值敏感的唯一约束?
【发布时间】:2013-05-04 16:23:43
【问题描述】:

问题来了:

我有一个这样的模型:

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

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

显然,该模型已经对字段 user 和 book 具有唯一的共同约束。并且可能在数据库中会有一些这样的条目:

    ------------------------------
    |user_id  book_id  is_active |
    |      1        1          0 |
    |      1        2          0 |
    |      1        3          1 |
    ------------------------------

我还有一个约束要添加,即每个用户最多可以有一个 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" %(self.user_id, self.is_active)
        else:
            self.key = "%s_%s_%s" %(self.user_id, self.is_active, self.book_id)

添加字段key,并自定义该模型的save方法。

但在这种方法中 ma​​x_length 不能大于 255(在我的情况下无需担心,但有时 key 字段可能很长)。

所以,我想知道是否有更优雅的方法来解决此类问题。

谢谢!

【问题讨论】:

    标签: python django django-models django-database


    【解决方案1】:

    在Django 2.2(当前发布为 beta1)中,您将能够使用UniqueConstraint,除了fields 列表之外,还可以传递condition

    一个 Q 对象,用于指定您希望约束强制执行的条件。

    例如,UniqueConstraint(fields=['user'], condition=Q(status='DRAFT') 确保每个用户只有一个草稿。

    【讨论】:

      【解决方案2】:

      根据 Nour 的回答,您可以这样做:

      class Meta:
          constraints = [
              models.UniqueConstraint(
                  fields=['user'],
                  condition=Q(is_active=True),
                  name='unique active user book per user'
              ),
          ]
      

      【讨论】:

      • 不幸的是,我收到了一个奇怪的错误could not create unique index 'unique user' as key(user, is_active)=(6,f) is duplicated. 我正在设置 is_active = True 但它也在检查非活动用户。
      【解决方案3】:

      将is_active重新定义如下:

      # Equals user ID if active; otherwise null.
      is_active = models.IntegerField(null = True, unique = True)
      

      用户 ID 在列中将是唯一的(满足您​​所需的约束),并且列中的许多空值不会违反约束,如 here 所讨论的那样。

      【讨论】:

        猜你喜欢
        • 2021-06-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-05
        • 2010-12-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多