[Fixed]-Django Admin, Show Aggregate Values From Related Model

26👍

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/

👤Bryan

Leave a comment