Ryan Eom
Ryan Eom

Reputation: 387

How to compare two fields in a CheckConstraint

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!

Upvotes: 13

Views: 2794

Answers (1)

Tajinder Singh
Tajinder Singh

Reputation: 1531

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",
            )
        ]

Upvotes: 15

Related Questions