How to make a query that filters rows in which one column is equal to another one table?

Let's say I have a model that looks like this:

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

Is there a way to make a django request that will show me all the requests where there is some relationship between amount_requested and amount_approved for a specific object / row?

In SQL, it will 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 this can be done, but I would suggest something like below (NOTE: the syntax is fully compiled and does not work).

 StockRequest.objects.filter(amount_requested="__amount_approved") 
+7
source share
3 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

+12
source

Yes, you can. You can use the built-in "F" object for this.

Syntax:

 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 right after I finished writing the question. Since I have not seen this in Qaru anywhere, I leave it with this answer.

+2
source

Note the docs function F() :

0
source

All Articles