4

So for a long time I've been doing annotations in ModelAdmins to add complicated number and related fields to list admin displays. Here's a simple count example.

class MyClassAdmin(admin.ModelAdmin):
    list_display [ .. 'capacity', ..]

    def get_queryset(self, request):
        return super(MyClassAdmin, self).get_queryset(request).annotate(
            capacity=Count('spaces')
        )

    def capacity(self, obj):
        return obj.capacity

In practice I'm doing four or five on some ModelAdmins. The query is slower than the stock query, but it's faster than doing 1+100 queries as the related data is pulled in.

However, Django does a count query on list views. Under the table you'll see a xxx modelnames message. This is generated from the same, annotated query. Verified with Django Debug Toolbar. I find that in some cases, any saving from reducing the number of queries is lost to the more complicated count query.

I know overriding get_queryset allows you to filter down the data but that's not how I'm using it. Is there something better I can override which allows the count to go through unannotated, but lets me annotate for the list display?

Oli
  • 235,628
  • 64
  • 220
  • 299
  • what is your RDBMS? – e4c5 Jun 27 '16 at 23:32
  • Both PostgreSQL and SQLite3. It happens in both. Not sure why that would matter for a ModelAdmin issue. – Oli Jun 28 '16 at 09:51
  • it matters greatly because count queries are executed differently by different RDBMS systems. On postgresql they are generally slow for large tables – e4c5 Jun 28 '16 at 09:51
  • Either which way, the problem here is that the ModelAdmin is executing the same subquery stuff (including the annotated count) both for the list (where I want that data) and the main count (where it matters naught). – Oli Jun 28 '16 at 11:04
  • Oli, I know that your question is 3 years old, but still ... you may want to check here https://hakibenita.com/things-you-must-know-about-django-admin-as-your-app-gets-bigger – Искрен Станиславов Mar 11 '19 at 17:21

0 Answers0