django admin list_display - returning multiple column values with single callable (django 1.9, python=2.7.x)
<p>So my Django code for <code>admin.py</code> looks something like this:</p>

<pre><code>class MyUserAdmin(UserAdmin):
    form = MyUseChangeForm
    list_display = ('email', 'is_admin', 'is_superuser', 
                    'total_tasks', 'total_tests')
    list_filter = ('is_admin', 'is_superuser')
    ordering = ('email',)

    def total_tests(self, obj):
        others = OtherObject.objects.filter(user=obj)
        total = 0
        correct = 0
        for other in others:
            # ... etc
        return # ...
    total_tests.short_description = "Tests Taken"

    def total_tasks(self, obj):
        return OtherObject.objects.filter(user=obj).count()
    total_tasks.short_description = "Tasks Done"
</code></pre>

<p>However, realizing that every callable I make (<code>total_tasks</code>, <code>total_tests</code>) will make this page load suuuuuuper slow when I have more database entries - is there a way to share computation? Maybe cache so that every callable doesn't have to query ALL the items from different tables over and over again?</p>

<p>Override the <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_queryset" rel="nofollow"><code>get_queryset</code></a> method for your <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#prefetch-related" rel="nofollow"><code>prefetch_related</code></a> to fetch the related objects. You can then modify your methods to use the prefetched <code>self.otherobject_set.all()</code> instead of querying <code>OtherObject.objects.filter(user=obj)</code> once for each method for each row in the queryset.</p>

<pre><code>class MyUserAdmin(UserAdmin):
    def get_queryset(self, request):
        qs = super(MyUserAdmin, self).get_queryset(request)
        qs = qs.prefetch_related('otherobject')
        return qs

    def total_tests(self, obj):
        others = self.otherobject_set.all()
        ...

    def total_tasks(self, obj):
        return len(self.otherobject_set.all())
</code></pre>

python django