Django GROUP BY字段值 [英] Django GROUP BY field value

查看:78
本文介绍了Django GROUP BY字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

令人惊讶的是,我找不到通过查询进行分组的方法。

Surprising that I could not find a way to make a group by query.

我有一个查询集 qs ,并且考虑到 qs 排除了 some_prop.val 分组> some_prop 是 None

I have a query set qs and I am trying to group by some_prop.val, considering qs is excluding entries where some_prop is None.

假设值是 [1、2、3] ,那么我就会得到这样的结果:

Let's say the values are [1, 2, 3], then I would be after a result like this:

{1: entries1, 2: entries2, 3: entries3}

Django ORM是否提供任何功能来分组结果是这样的吗?

Does the Django ORM provide any feature to group results like this?

推荐答案

(据我所知)没有特定的Django ORM方式,但是您可以以下是获得按字段值分组的条目字典的方法:

There is not a specific Django ORM way (as far as I know) but you can do the following to get a dictionary of entries grouped by values of a field:


  1. 使用 .values_list() flat = True 获取数据中现有值的列表基础(如果您事先不了解它们)。还可以使用 .distinct()消除重复的值,因为我们不在乎那些值:

  1. Use .values_list() with flat=True to get a list of the existent values in your database (if you don't know them beforehand). Also use .distinct() to elimintae duplicate values as we do not care for those:

value_list = MyModel.objects.values_list(
    'interesting_field', flat=True
).distinct()


  • 现在遍历 value_list 并填写您的字典:

    group_by_value = {}
    for value in value_list:
        group_by_value[value] = MyModel.objects.filter(interesting_field=value)
    


  • 现在 group_by_value 字典包含 interesting_field 中不同的值作为键,并包含queryset对象的值,每个对象都包含 MyModel 中带有 interesting_field = value_list中的值

    Now group_by_value dictionary contains as keys the distinct values in your interesting_field and as values the queryset objects, each containing the entries of MyModel with interesting_field=a value from value_list.






    出于遗留评论的原因而将其保留在此处。

    我做了一个 Q& A样式示例,其中模拟了 COUNT ... GROUP BY SQL查询。

    I have made a Q&A style example in, which simulates a COUNT ... GROUP BY SQL query.

    本质上,您需要使用 .order_by 进行分组和 。 annotate() 依靠模型的 .values()

    Essentially you need to utilize the .order_by for grouping and the .annotate() to count on the model's .values().

    以下是上述示例:


    我们可以在Django ORM上执行 COUNT ... GROUP BY 个SQL等效查询,并使用 annotate() values() order_by()
    dj ango.db.models Count 方法:

    We can perform a COUNT ... GROUP BY SQL equivalent query on Django ORM, with the use of annotate(), values(), order_by() and the django.db.models's Count methods:

    让我们的模型为:

    class Books(models.Model):
        title  = models.CharField()
        author = models.CharField()
    

    让我们假设我们要计算每个不同作者中有多少本书对象图书表:

    Lets assume that we want to count how many book objects per distinct author exist in our Book table:

    result = Books.objects.values('author')
                          .order_by('author')
                          .annotate(count=Count('author'))
    

    现在的结果包含一个查询集有两列:作者和计数:

    Now result contains a queryset with two columns: author and count:

      author    | count
    ------------|-------  
     OneAuthor  |   5 
    OtherAuthor |   2    
       ...      |  ...
    


    这篇关于Django GROUP BY字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆