在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'))
作为管理员更改列表的全局变量...
答案 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'))