Home > Back-end >  How to use order_by when using Django group_by, take out all fields
How to use order_by when using Django group_by, take out all fields

Time:05-19

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')

CodePudding user response:

You can try this.

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

CodePudding user response:

try window function and subquery

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')]))
        .values('first_id')))

  • Related