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

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


Solution 1:[1]

You can try this.

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 David Lu