bharath bhushan
bharath bhushan

Reputation: 217

Django ORM - filter method with some arithmetic calculation

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

Answers (2)

Matt Seymour
Matt Seymour

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

bharath bhushan
bharath bhushan

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

Related Questions