How to intersect two query sets in django?
I have two queries. One of them has sold product id and sale amount, other one has product id and product price.
query_product = Model1.objects.filter(...).values_list('ProductID', 'ProductPrice')
query_sale = Model2.objects.filter(...).values_list('SaleProductID', 'ProductAmount')
I want to calculate IF SaleProductID = ProductID, Sum(F('ProductPrice')*F('ProductAmount'). However, I could not find how to do that with query. Note: Model2 has foreign key to Model1.
Do you have any suggestions? Thank you!
This might help:
from django.db.models import Subquery, IntegerField
class SQSum(Subquery):
output_field = IntegerField()
template = "(SELECT sum(PBGelSipUrunAdet) from (%(subquery)s) _sum)"
accumulated_quantity_subquery = SQSum(
PBGelenSiparisUrun.objects.filter(
pburun=OuterRef('id')
).values("PBGelSipUrunAdet")
)
queryset = PBUrun.objects.annotate(
total_quantity=accumulated_quantity_subquery,
amount=F("PBUrunPrice") * F("total_quantity")
)
This will Annotate amount for each Product.