Skip to content Skip to sidebar Skip to footer

Django Admin List_display - Returning Multiple Column Values With Single Callable (django 1.9, Python=2.7.x)

So my Django code for admin.py looks something like this: class MyUserAdmin(UserAdmin): form = MyUseChangeForm list_display = ('email', 'is_admin', 'is_superuser',

Solution 1:

First of all tune tune your code.

  1. total_tasks - should be OtherObject.objects.filter(user_id=obj.pk).count() - it will boost you a bit.
  2. You've hidden the body of for loop in total_tests. I am afraid that you refer to some objects connected with OtherObject model. Without select_related you can almost DDOS your database and make the view extremaly slow.

Solution 2:

Override the get_queryset method for your prefetch_related to fetch the related objects. You can then modify your methods to use the prefetched self.otherobject_set.all() instead of querying OtherObject.objects.filter(user=obj) once for each method for each row in the queryset.

classMyUserAdmin(UserAdmin):
    defget_queryset(self, request):
        qs = super(MyUserAdmin, self).get_queryset(request)
        qs = qs.prefetch_related('otherobject')
        return qs

    deftotal_tests(self, obj):
        others = self.otherobject_set.all()
        ...

    deftotal_tasks(self, obj):
        returnlen(self.otherobject_set.all())

Post a Comment for "Django Admin List_display - Returning Multiple Column Values With Single Callable (django 1.9, Python=2.7.x)"