Reputation: 3489
I wonder if the way I calculate quantity * price_gross
is the right way to do it. Or is there a better way to multiply these values inside the Ticket.objects.
query set?
event = Event.objects.get(pk=4)
test = Ticket.objects.filter(event=event).values('quantity', 'price_gross')
result = 0
for x in test:
result += x['quantity']*x['price_gross']
print(result)
Updated:
Ticket.objects.filter(
event__organizer__in=self.organizers,
event__status=EventStatus.LIVE,
).values('event__pk', 'pk')
.order_by('event__pk')
.annotate(
total_gross=F('quantity') * F('price_gross'),
)
.aggregate(Sum('total_gross'))
Upvotes: 2
Views: 148
Reputation: 31260
You can go one further and also do the summing in the database (untested! but should more or less work):
from django.db.models import F, Sum
result = (
Ticket.objects.filter(event=event)
.values('quantity', 'price_gross')
.annotate(total=F('quantity') * F('price_gross'))
.aggregate(Sum('total'))
)
Upvotes: 1
Reputation: 2046
Yes. There's indeed a way of doing that and it's by using Query Expressions
test = Ticket.objects.filter(event=event).annotate(total=F('quantity') * F('price_gross'))
Upvotes: 1