Marko Maksimovic
Marko Maksimovic

Reputation: 87

Django query to dict with corresponding values

I'm working on a shop project and want to be able to see what most sold products on my shop are.

Here is my models.py

class Product(models.Model):
    #some values like name, price, etc...

class Purchase(models.Model):
    purchase_completed = models.BooleanField(default=False)
    # This is the only important field for this model regarding the problem that I Have
    # Other fields include stuff like buyers info, end price, etc...


class PurchaseContains(models.Model):
    #Every product has its amount, purchase its related to and the product of course, with some other values as well, but not related to the problem I'm having 
    product = models.ForeignKey(Product...) 
    purchase = models.ForeignKey(Purchase...)
    amount = models.PositiveIntegerField(blank=False, null=False)

Now what I want is to do a query thats going to give me what Products from PurchaseContains are bought the most (by amount from the table) and also the Purchase itself must be completed (purchase_completed==True in Purchase for the given product in PurchaseContains)

Now this is what I have done:

sold_the_most= PurchaseContains.objects.filter(purchase__purchase_completed=True).values("product", 'amount')
sold_the_most_dict= {}
for i in sold_the_most:
    sold_the_most_dict[i["product"]] = sold_the_most_dict.get(i['product'], 0)+i["amount"]

As you can see I get the products and amount for purchases that are completed and then do the loop for it to get them in the dictionary.

Now this does work and it gives me the output that I can work with, but I'm sure that there is a better solution for it. Some query that can maybe give me the data in the form that looks something like [[product, amount], [product, amount], ...] (not expecting it like this straight away, but you get the point).

I have searched for a long time and the solution that you see is the best I came up with, because I'm not too familiar with Django queries.

Upvotes: 0

Views: 2354

Answers (1)

ruddra
ruddra

Reputation: 51938

Probably you want something like a GROUP_BY in SQL. It is possible to do that in Django using aggregation features of the ORM:

from django.db.models import Sum

values = PurchaseContains.objects.filter(purchase__purchase_completed=True).values("product").annotate(total=Sum("amount")).values('product','total')
print(values)

Upvotes: 1

Related Questions