Django Admin: Order by value on related Foreign Key

后端 未结 3 1478
孤独总比滥情好
孤独总比滥情好 2021-01-05 11:35

I\'m trying to sort a Django Admin list page by a specific value in the objects\' related foreign key set.

Specifically, in the below code, I want the ContentAdmin v

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-05 12:02

    I solved this by extending the get_queryset method of the ContentAdmin class. After that, it was just a matter of getting the right ORM query

    def get_queryset(self, request):
        qs = super(ContentAdmin, self).get_queryset(request)
        return qs.filter(score__name='Twitter').order_by('-score__score')
    

    For Django 1.5 and earlier, the method was queryset.

    def queryset(self, request):
        qs = super(ContentAdmin, self).queryset(request)
        return qs.filter(score__name='Twitter').order_by('-score__score')
    

提交回复
热议问题