【问题标题】:How do I make a list of field values on annotated Django queryset results?如何在带注释的 Django 查询集结果上列出字段值?
【发布时间】:2019-12-19 03:17:23
【问题描述】:

这可能在某个地方,但不太确定如何询问。希望这将是一个快速的。假设我有一个如下表:

name         count   site
Guy Man      2       ABC
Guy Man      3       BCD
Guy Man      4       CDE
Girl Woman   2       ABC
Girl Woman   2       BCD
Girl Woman   3       CDE

我想对这些进行注释,以便获得名称、总数和站点列表。所以根据上面的数据,我会得到以下数据。

[
  {
    "name": "Guy Man",
    "count_total": 9,
    "site_list": "ABC, BCD, CDE"
  },
  {
    "name": "Girl Woman",
    "count_total": 7,
    "site_list": "ABC, BCD, CDE"
  }
]

我了解如何获取count_total,但我不确定如何获取site_list。有什么想法吗?

【问题讨论】:

    标签: django django-queryset django-annotate


    【解决方案1】:

    PostgreSQL 按名称字段结合ArrayAggdistinct=True 标志分组的解决方案:

    from django.contrib.postgres.aggregates.general import ArrayAgg
    from django.db.models import Count
    
    Model.objects.values('name').annotate(
        count_total=Count('count'),
        site_list=ArrayAgg('site', distinct=True),
    )
    

    【讨论】:

      【解决方案2】:

      如果你使用 postgres,你可以使用 ArrayAgg

      文档 - https://docs.djangoproject.com/en/2.2/ref/contrib/postgres/aggregates/

      您可以使用值进行分组,如下所示应该可以解决问题。 Model.objects.values('name').distinct().annotate(site_list=ArrayAgg('site'), count_total=Count('count'))

      【讨论】:

        猜你喜欢
        • 2020-06-13
        • 1970-01-01
        • 2020-07-04
        • 1970-01-01
        • 2017-08-29
        • 2020-05-14
        • 2021-10-17
        • 1970-01-01
        • 2020-05-09
        相关资源
        最近更新 更多