如何在Django中为组使用值和注释时获取其他字段数据

How to get other field data when using values and annotate for the group in Django

我想为特定品牌的每个 product_type_id 获取 1 件产品。 所以,我写了这个查询 returns 正确的输出,但在我的产品模型中,还有其他几个字段如 product_name、product_info 等无法访问,为什么?它只有 returns product_type_id & 价格。

plans_data = Product.objects.filter(brand__brand_id = brand_data_1.brand_id).values('product_type_id').annotate(min_brand_price=Min('product_price'))

我认为你可以分两步实现你的目标,

  1. 使用您的查询但添加产品 ID
  2. 使用第 1 步的所有产品 ID 使用 in 运算符过滤产品

像这样,

plans_id = Product.objects.filter(brand__brand_id = brand_data_1.brand_id).values('product_type_id').annotate(min_brand_price=Min('product_price'), min_id=Min('product_id'))
plans_data = Product.objects.filter(product_id__in=[plan_id['min_id'] for plan_id in plans_id])

这里有一些结合注释的例子Django Docs - Expressions