RaccoonONRoids
RaccoonONRoids

Reputation: 47

How to order by a value calculated based on some other model in Django?

For eg:

Model Company has fields: company_name and stock_price

Model Products has fields: product_price and company_name

I want to do something like: Company.objects.order_by( stock_price / [divided by] Products.objects.filter(company_name = Company__companyName).aggregate(Sum('product_price')).get('product_price__sum'))

Essentially, what I want to do is divide the stock price of company X by the aggregate of product_price of the products of company X and use the resulting calculation to order all the objects of Company. Where company_name is the foreign key.

I just want to know if doing such a thing is possible in Django. Thanks!

Upvotes: 1

Views: 89

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477794

You can sort the companies by:

from django.db.models import F, Sum

Company.objects.order_by(
    (F('stock_price')/Sum('products__product_price')).asc()
)

or prior to , you first annotate and then .order_by(…):

from django.db.models import F, Sum

Company.objects.annotate(
    order=F('stock_price')/Sum('products__product_price')
).order_by('order')

Upvotes: 1

Related Questions