如何比较 CheckConstraint 中的两个字段

Rya*_*Eom 10 django django-models

如果这是我的模型:

class Bid(models.Model):

    amount = models.DecimalField(max_digits=11, decimal_places=2)
    starting_bid = models.DecimalField(max_digits=11, decimal_places=2, null=True)
Run Code Online (Sandbox Code Playgroud)

如何添加一个约束来检查金额字段是否大于或等于起始出价?这就是我现在所拥有的:

class Meta:
    constraints = [
        models.CheckConstraint(check=Q(amount > starting_bid), name='amount_gte_starting_bid')
    ]
Run Code Online (Sandbox Code Playgroud)

这当然是不正确的。谢谢你!

Taj*_*ngh 12

使用 F() 对象来引用模型中的字段。从这里: https: //adamj.eu/tech/2020/03/10/django-check-constraints-sum-percentage-fields/

class Meta:
        constraints = [
            models.CheckConstraint(
                check=models.Q(
                    amount__gte=models.F("starting_bid")                        )
                ),
                name="amount_gte_starting_bid",
            )
        ]
Run Code Online (Sandbox Code Playgroud)

  • 模型属性直接实现像“>=”这样的比较运算符在哪里有记录?我收到“TypeError: 'DeferredAttribute' 和 'F' 实例之间不支持 '<='`。我认为应该是`amount__gte=models.F("starting_bid")`。 (7认同)