简体   繁体   中英

How to make GROUP BY query with Many To Many Fields in Django

I want to make a request to select the number of total quantity per product. The models look like this:

class Products(models.Model):
      name = models.CharField(max_length=200)

class Orders(models.Model):
      product = models.ManyToManyField(Products, through='OrdersQuantities')

class OrdersQuantities(models.Model):
      quantity = models.IntegerField()
      product = models.ForeignKey(Products, on_delete=models.DO_NOTHING)
      order = models.ForeignKey(Orders, on_delete=models.DO_NOTHING)

And the SQL query I want to make in Django using Orders model

SELECT name, SUM(quantity) AS qte
FROM products, ordersquantities
WHERE ordersquantities.product_id = product.id
GROUP BY name ORDER BY qte DESC

Thank you for reading!

You can .annotate(…) [Django-doc] the Products queryset with:

Products.objects.annotate(
    
)

The Products objects that arise from this queryset, will have an extra attribute .qte that contains the sum of the quantity s of the related OrdersQuantities .

We can also list the Product s with the corresponding quantities for a given order:

Products.objects.filter(
    
).annotate(
    qte=Sum('ordersquantities__quantity')
)

Here we thus will not count OrdersQuantities that do not belong to the some_order_object .


Note : normally a Django model is given a singular name, so OrdersQuantity instead of OrdersQuantities .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM