Reputation: 217
I have the following query which I am trying to turn into a django ORM query.
SELECT * FROM products WHERE discontinued = 0 AND ((unitsinstock + unitsonorder) < reorderlevel)
I tried the following python code but with no success.
products = Products.objects.filter(
discontinued=0, (unitsinstock + unitsonorder < reorderlevel)
)
Upvotes: 0
Views: 419
Reputation: 9395
Take a look at the F() expressions
and the annotate
function found within the ORM. It will allow you to do what you want to do.
products = Products.objects.filter(discontinued=0).annotate(
currentlevel=Sum(F("unitsinstock") + F("unitsonorder"))
).filter(reorderlevel__gt=F("currentlevel"))
Upvotes: 1
Reputation: 217
F() expression helped to solve this, Below query worked perfectly
Products.objects.filter(
discontinued =0,
reorderlevel__gt = F("unitsinstock") + F("unitsonorder")
)
Upvotes: 1