Cory
Cory

Reputation: 24260

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

Upvotes: 9

Views: 4153

Answers (3)

Don
Don

Reputation: 17606

Check docs on the F() function:

Upvotes: 0

Cory
Cory

Reputation: 24260

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.

Upvotes: 2

vartec
vartec

Reputation: 134581

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

Upvotes: 15

Related Questions