Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Admin, Show Aggregate Values From Related Model

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?

like image 231
Ben Avatar asked Sep 01 '11 21:09

Ben


1 Answers

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/

like image 172
Bryan Avatar answered Sep 22 '22 07:09

Bryan