代码之家  ›  专栏  ›  技术社区  ›  Milano

Django-确保每个用户只有一个活动产品

  •  0
  • Milano  · 技术社区  · 5 年前

    有这个模型吗

    class Product(models.Model):
        user = models.ForeignKey(...)
    
        STATUS_ACTIVE = 'active'
        STATUS_CANCELLED = 'cancelled'
        STATUS_DRAFT = 'draft'
        STATUS_CHOICES = (
            (STATUS_ACTIVE,'Active'),
            ...
        )
        status = models.CharField(..., choices=STATUS_CHOICES)
    

    我在想办法 User 只有一种产品的型号 ACTIVE . 用户 允许有任何数量的 CANCELLED DRAFT 产品,但只能有一个 活跃的 .

    我在想 CheckConstraint

    1 回复  |  直到 5 年前
        1
  •  2
  •   willeM_ Van Onsem    5 年前

    你可以用 UniqueConstraint status 处于活动状态:

    from django.db.models import Q
    
    class Product(models.Model):
        user = models.ForeignKey(…)
    
        STATUS_ACTIVE = 'active'
        STATUS_CANCELLED = 'cancelled'
        STATUS_DRAFT = 'draft'
        STATUS_CHOICES = (
            (STATUS_ACTIVE,'Active'),
            …
        )
        status = models.CharField(…, choices=STATUS_CHOICES)
        class Meta:
            constraints = [
                UniqueConstraint(
                    fields=['user'],
                    condition=Q(status=STATUS_ACTIVE),
                    name='one_user_per_active_product'
                )
            ]

    condition=… parameter [Django-doc] 是从 而且,并不是所有的数据库本身都强制执行这些约束。

    推荐文章