Django GROUP BY Field Value

Surprisingly, I could not find a way to make the group on request.

I have a set of queries qs, and I'm trying to group by some_prop.val, given that it qsexcludes entries where some_propthere are None.

Let's say that the values [1, 2, 3], then I would get the following result:

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

Does Django ORM provide any function for grouping such results?

+1
source share
1 answer

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

  • .values_list() flat=True, ( " ). .distinct() , :

    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 , MyModel interesting_field=a value from value_list.




.

Q & a style, COUNT ... GROUP BY SQL.

.order_by .annotate(), .values().

:

COUNT ... GROUP BY SQL- Django ORM annotate(), values(), order_by() django.db.models Count :

:

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

, , :

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

: author count:

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

Source: https://habr.com/ru/post/1736749/


All Articles