Reputation: 47
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
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 django-2.2, 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