Django管理列表显示优化查询集

时间:2015-03-09 13:28:49

标签: python django optimization admin django-queryset

User模型中我有一个方法:

@cached_property
    def income(self):
        return PartnerIncome.objects.all().aggregate(Sum('income'))['income__sum']*self.share_of_profit

PartnerIncome模型:

class PartnerIncome(models.Model):
    title = models.CharField(max_length=255)
    income = models.FloatField(default=0)

现在我想在管理面板的list_display=('income', )中显示'inccome',但每个对象都会对数据库进行额外查询。如何将PartnerIncome.objects.all().aggregate(Sum('income'))作为管理员更改列表的全局变量...

1 个答案:

答案 0 :(得分:7)

如何覆盖get_queryset中的ModelAdmin方法?

class UserAdmin(admin.ModelAdmin):

    list_display = ('income', ...)

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

    def get_queryset(self, request):
       queryset = super(UserAdmin, self).get_queryset(request)
       # you logic here to `annotate`the queryset with income
       return queryset

aggregation上的文档:

https://docs.djangoproject.com/en/dev/topics/db/aggregation/

没有我真正理解你的模型和业务逻辑..这里是我自己代码的一个片段作为例子:

class AuthorAdmin(admin.ModelAdmin):
    list_display = ('__str__', 'books_count',)

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

    def get_queryset(self, request):
        return super(AuthorAdmin, self).get_queryset(
            request).annotate(books_count=Count('books'))