我有这种模型:
class OrderProducts(models.Model):
product = models.ForeignKey(Product)
quantity = models.IntegerField()
...
我需要计算有多少 OrderProducts 拥有相同的产品。它正在使用这一行:
ordersProduct = OrderProducts.objects.prefetch_related('product_set')\
.filter(my-filter)\
.values('product','product__title')\
.annotate(total=Count('product'))\
.order_by('-total')
这条线有效,我知道我有多少相同的 OrdersProduct。但是,我需要为每个 OrdersProduct 添加总数量以及每个 orderProduct 的数量。
如果我有 3 次相同的 OrderProduct,其中包含相同的产品,我想知道这 3 次查询的每个数量的数量(总计)。
谢谢!
编辑:
它正在处理这个:
ordersProduct = OrderProducts.objects.prefetch_related('product_set')\
.filter('my-filter')\
.values('product','product__title')\
.annotate(total_ordered=models.Sum('quantity'),num_orders=models.Count('product'))
最佳答案
这就是你想要的吗?
class OrderProducts(models.Model):
product = models.ForeignKey(Product, related_name='orders')
Product.objects.annotate(total_ordered=models.Sum('orders__quantity'),
num_orders=models.Count('orders__id'))
关于python - Django 按查询集分组并与另一个字段相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34709011/