10

If this is my model:

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)

How do I add a constraint that checks if the amount field is greater than or equal to the starting bid? This is what I have now:

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

Which of course is not correct. Thank you!

Ryan Eom
  • 337
  • 3
  • 14

1 Answers1

12

Use F() objects to refer to the fields in your model. From here: 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",
            )
        ]
dfrankow
  • 20,191
  • 41
  • 152
  • 214
Tajinder Singh
  • 1,361
  • 2
  • 14
  • 26
  • 7
    Where is it documented that model attributes directly implement comparison operators like `>=`? I get `TypeError: '<=' not supported between instances of 'DeferredAttribute' and 'F'`. I think it should be `amount__gte=models.F("starting_bid")`. – Feuermurmel Aug 31 '21 at 14:03