How to use order_by when using group_by in Dajngo-orm, and take out all fields

Viewed 50

I used Django-orm,postgresql, Is it possible to query by group_by and order_by?

this table


| id | b_id | others |

| 1 | 2 | hh |
| 2 | 2 | hhh |
| 3 | 6 | h |
| 4 | 7 | hi |
| 5 | 7 | i |

I want the query result to be like this

| id | b_id | others |

| 1 | 2 | hh |
| 3 | 6 | h |
| 4 | 7 | hi |

or

| id | b_id | others |

| 4 | 7 | hi |
| 3 | 6 | h |
| 1 | 2 | hh |

I tried

Table.objects.annotate(count=Count('b_id')).values('b_id', 'id', 'others')
Table.objects.values('b_id', 'id', 'others').annotate(count=Count('b_id'))

Table.objects.extra(order_by=['id']).values('b_id','id', 'others')
2 Answers

You can try this:

from django.db.models import Count
result = Table.objects
    .values('b_id')
    .annotate(count=Count('b_id'))

Try window function and subquery in the following way:

from django.db.models import Window, F, Subquery, Count
from django.db.models.functions import FirstValue

queryset = A.objects.annotate(count=Count('b_id')).filter(pk__in=Subquery(
    A.objects.annotate(
        first_id=Window(expression=FirstValue('id'), partition_by=[F('b_id')]), order_by=F('id'))
        .values('first_id')))

Related