开发者

Django Group By relation's data

开发者 https://www.devze.com 2022-12-20 04:21 出处:网络
In Django, I can do value(), and then distinct() to group by. A { Foreign Key B } B { Stri开发者_运维问答ng name

In Django,

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

A
{
     Foreign Key B
}
B
{
     Stri开发者_运维问答ng 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?


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

精彩评论

暂无评论...
验证码 换一张
取 消