django admin list_display - 使用单个可调用返回多个列值(django 1.9,python = 2.7.x) [英] django admin list_display - returning multiple column values with single callable (django 1.9, python=2.7.x)

查看:151
本文介绍了django admin list_display - 使用单个可调用返回多个列值(django 1.9,python = 2.7.x)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我的Django代码 admin.py 看起来像这样:

So my Django code for admin.py looks something like this:

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"

然而,意识到每个可调用我( total_tasks total_tests )将使这个pa当我有更多的数据库条目时,ge load suuuuuuper缓慢 - 有没有办法共享计算?也许缓存,以便每个可调用都不必一次又一次地从不同的表中查询所有的项目。

However, realizing that every callable I make (total_tasks, total_tests) 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?

推荐答案

get_queryset 方法为您的 prefetch_related 来获取相关对象。然后,您可以修改方法以使用预取的 self.otherobject_set.all()而不是查询 OtherObject.objects.filter(user = obj)一次对于queryset中的每一行的每个方法。

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.

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())

这篇关于django admin list_display - 使用单个可调用返回多个列值(django 1.9,python = 2.7.x)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆