[英]How to make GROUP BY query with Many To Many Fields in Django
我想请求选择每个产品的总数量。 模型如下所示:
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)
以及我想在 Django 中使用Orders
模型进行的 SQL 查询
SELECT name, SUM(quantity) AS qte
FROM products, ordersquantities
WHERE ordersquantities.product_id = product.id
GROUP BY name ORDER BY qte DESC
感谢您的阅读!
你可以.annotate(…)
[Django-doc] Products
:
Products.objects.annotate(
qte=Sum('ordersquantities__quantity')
).order_by('-qte')
从此查询集产生的Products
对象将有一个额外的属性.qte
,其中包含相关OrdersQuantities
的quantity
之和。
我们还可以列出具有给定订单相应数量的Product
:
Products.objects.filter(
ordersquantities__order=
).annotate(
qte=Sum('ordersquantities__quantity')
).order_by('-qte')
在这里,我们因而不会计算OrdersQuantities
不属于some_order_object
。
注意:通常 Django 模型被赋予一个单数名称,因此
OrdersQuantity
而不是。OrdersQuantities
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.