Joey Coder
Joey Coder

Reputation: 3489

Django: Multiply inside query set

I wonder if the way I calculate quantity * price_grossis 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

Answers (2)

RemcoGerlich
RemcoGerlich

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

Higor Rossato
Higor Rossato

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

Related Questions