Django Admin, Show Aggregate Values From Related M

2020-03-01 08:51发布

Is it possible, within a single Django admin model, to aggregate fields from related objects.

For example, I have a Student Object that has a FK to a Test Object. The test object has a "score" field.

Can I aggregate the scores across all Student's Tests and place it in the admin display_list attribute?

1条回答
虎瘦雄心在
2楼-- · 2020-03-01 09:06

You can, for example:

class FixtureAdmin(admin.ModelAdmin): 
    list_display = ["id", "title", "date", "num_fixture_metas_count"]

    def get_queryset(self, request):
        qs = super(FixtureAdmin, self).get_queryset(request)
        return qs.annotate(num_fixture_metas=Count('fixturemeta'))

    def num_fixture_metas_count(self, obj):
      return obj.num_fixture_metas
    num_fixture_metas_count.short_description = 'Fixture Count'
    num_fixture_metas_count.admin_order_field = 'num_fixture_metas'

However, AFAIK, you cannot click sort within the admin on these fields via this method, as adding num_fixture_metas from .annotate() to the list_display results in a missing field error.

https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display https://docs.djangoproject.com/en/dev/topics/db/aggregation/

查看更多
登录 后发表回答