python - Django 按查询集分组并与另一个字段相乘

标签 python mysql sql django

我有这种模型:

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/

相关文章:

python - 在 Spark Streaming 中查找中位数

mysql - 在 MySQL 中选择与按 Id 增量分组的条件匹配的行数

sql - 如何使用 MySQL 进行分组和计数

sql - 查询 SSRS 数据集中的 View 与表

sql - "Adding"GROUP BY 's and ORDER BY' 在一个查询中而不是单独的

python - 将对数正态分布拟合到已经装箱的数据 python

python - TensorFlow per_image_standardization 与整个数据集的平均标准化

python - 了解 scikit CountVectorizer 中的 min_df 和 max_df

mysql - ON 子句中另一个未知列名错误

MySQL 从满足条件的行中选择字段,并从上面的行中选择字段