belisasun
belisasun

Reputation: 565

How to get the sum of the prices of all items in the Magazine? - django ORM

class Item(models.Model):
    name = models.CharField(max_length=50)
    item_price = models.DecimalField(max_digits=5, decimal_places=2)

class Magazine(models.Model):
    name = models.CharField(max_length=50)
    items = models.ManyToManyField('Item', blank=True, null=True)
    owner = models.ForeignKey(User, related_name='u_item')

How to get the sum of the prices of all items in the Magazine?

in views:

...
    user = request.user
    magazins = Magazine.objects.filter(owner= user)
...

Upvotes: 1

Views: 1311

Answers (2)

Pratik Mandrekar
Pratik Mandrekar

Reputation: 9568

Start by taking a look at aggregations in Django.

It might look something like below:

from django.db.models import Sum
owners_magazines = Magazine.objects.filter(owner='Your owner')
total = 0;
for magazine in owners_magazines:
    item_values_with_total = magazine.items.values().annotate(total=Sum('item_price'))
    total += <Read appropriately from item_values_with_total>

You can use further try to group things together. The returned value will have a field called total which will have the required sum.

Edit -

You can try a non-ORM solution to understand it better

from django.db.models import Sum
    owners_magazines = Magazine.objects.filter(owner='Your owner')
    total = 0;
    for magazine in owners_magazines:
        all_items = magazines.items_set.all()
        for item in all_items:
            total += item.item_price

    print total

Upvotes: 1

Burhan Khalid
Burhan Khalid

Reputation: 174624

Use aggregation:

from django.db.models import Sum

for m in Magazine.objects.all():
   total = m.items_set.all().annotate(total=Sum('item_price'))
   print 'Total cost for items in {0} is {1}'.format(m,total)

Upvotes: 1

Related Questions