Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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")
like image 590
Cory Avatar asked May 04 '11 16:05

Cory


2 Answers

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

http://docs.djangoproject.com/en/dev/topics/db/queries/#filters-can-reference-fields-on-the-model

like image 109
vartec Avatar answered Nov 13 '22 23:11

vartec


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.

like image 28
Cory Avatar answered Nov 13 '22 23:11

Cory