Is it possible, within a single Django admin model, to aggr开发者_JAVA技巧egate 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?
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/
精彩评论