Django Admin: Order by value on related Foreign Key

后端 未结 3 1512
孤独总比滥情好
孤独总比滥情好 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:20

    Since django admin uses the db to sort you cant sort on the function you are showing in the list.

    What you can do is to add the column you want to show to the queryset that django admin is using to list your models, this way you can have sorting.

    To add the column you need you have to use the queryset extra method.

    This should do the trick :)

    Content.objects.all().extra(select={'twitter_score': 'SELECT score from content_score WHERE content_score.id = content_content.id'})
    

    BONUS ROUND:

    Content.objects.all().extra(select={'twitter_score': 'SELECT 'Twitter score:' || score from content_score WHERE content_score.id = content_content.id'})

提交回复
热议问题