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)
)
CodePudding user response:
F() expression helped to solve this, Below query worked perfectly
Products.objects.filter(
discontinued =0,
reorderlevel__gt = F("unitsinstock") F("unitsonorder")
)
CodePudding user response:
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"))
