views:

46

answers:

1

In Django,

I can do value(), and then distinct() to group by.

A
{
     Foreign Key B
}
B
{
     String name
}

However, is it possible to group using a related object's data? I.e. In the above relation, can I group A by B's name?

A: 

I think you can order_by on the FKey model.

A.objects.order_by('B__name')

Iff you can't, You need to use the Django ORM's Annotation API, to make a new field and you will be able to order it accordingly:

A.objects.annotate(bname='B__name').order_by('bname')
Lakshman Prasad
The 1st one works. The 2nd one doesn't becaus annotate requires an aggregation inside it.Thanks
jameszhao00