Alex Rivera | Logout

How to make a query that filters rows in which one column equals another one of the same table?

Asked 2011-05-04T16:40:45.907
9

Say I have a model that looks like:

class StockRequest(models.Model):
    amount_requested = models.PositiveIntegerField(null=True)
    amount_approved = models.PositiveIntegerField(null=True) 

Is there any way to make a django query that would show me all requests where there is some relationship between amount_requested and amount_approved on a particular object/row?

In SQL it would be as simple as:

select * from stockrequest where amount_requested = amount_approved;

or

select * from stockrequest where amount_requested = amount_approved;

In Django, I'm not sure if it can be done, but I would imagine something like the below (NOTE: syntax completely made up and does not work).

StockRequest.objects.filter(amount_requested="__amount_approved")
Edit
Report

1 Answer

2

Yes, you can. You can use the built in "F" object to do this.

The syntax would be:

from django.db.models import F
StockRequest.objects.filter(amount_requested=F("amount_approved"))

or

StockRequest.objects.filter(amount_requested__gt=F("amount_approved"))

Note: I found the answer immediately after I finished writing the question up. Since I hadn't seen this on Stack Overflow anywhere, I am leaving it up with this answer.

answered 2011-05-04T16:44:47.983

Your Answer