【问题标题】:How to get other field data when using values and annotate for the group in Django在Django中使用值和注释时如何获取其他字段数据
【发布时间】:2020-06-13 08:21:45
【问题描述】:

我想为特定品牌的每个 product_type_id 获取 1 个产品。 所以,我写了这个查询,它返回正确的输出,但在我的产品模型中,还有其他几个字段,如 product_name、product_info 等无法访问,为什么?它只返回 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'))

【问题讨论】:

标签: django django-models django-views django-orm


【解决方案1】:

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

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

类似的,

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

【讨论】:

  • 无法正常工作,显示此错误 'Min' object has no attribute 'annotate'
  • 对不起,我已经编辑了答案,这个想法是保留和 id 除了你已经拥有的值,所以以后你可以通过获取 id 来获取这些对象.. 自从我不这样做已经有一段时间了'不使用注释
  • 感谢您的回答,但仍然抛出 KeyError
  • 谢谢现在它正在工作我用名称 min_id 更改了密钥
  • 太好了,很高兴它对你有帮助!谢谢你的建议!!
猜你喜欢
  • 2018-10-07
  • 1970-01-01
  • 2022-01-25
  • 2017-12-18
  • 2018-07-21
  • 1970-01-01
  • 2011-11-10
  • 2021-11-03
  • 1970-01-01
相关资源
最近更新 更多