您可以将
Model或
ModelAdmin作为的项目使用方法
list_display。参见:https
:
//docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display
由于这些方法在管理员外部也可能有用,因此建议您将它们添加到
Model。
from django.db.models import Sumclass Data(models.Model): ... # Method used by `get_current_year_sales` and `get_last_year_sales` # to stay DRY. Not for use directly in admin. def get_year_sales(self, year): qs = self.model._default_manager.filter(year=year) sales_agg = qs.aggregate(Sum('sales')) return sales_agg['sales__sum'] # Method used by `get_current_quarter_sales` and `get_last_quarter_sales` # to stay DRY. Not for use directly in admin. def get_quarter_sales(self, year, quarter): qs = self.model._default_manager.filter(year=year, quarter=quarter) sales_agg = qs.aggregate(Sum('sales')) return sales_agg['sales__sum'] def get_current_year_sales(self): return self.get_year_sales(datetime.now().year) get_current_year_sales.short_description = 'Sales (Current Year)' def get_last_year_sales(self): return self.get_year_sales(datetime.now().year-1) get_last_year_sales.short_description = 'Sales (Last Year)' def get_current_quarter_sales(self): # Determine current quarter logic here as `current_quarter` # `quarter_year` will likely be same as current year here, # but will need to be calculated for previous quarter return self.get_quarter_sales(quarter_year, current_quarter) get_current_quarter_sales.short_description = 'Sales (Current Quarter)' def get_current_quarter_sales(self): # Logic here to determine last quarter as `last_quarter` # Logic to determine what year last quarter was in as `quarter_year` return self.get_quarter_sales(quarter_year, last_quarter) get_last_quarter_sales.short_description = 'Sales (Last Quarter)'
该
short_description属性确定管理员将显示为这些方法的行标题的内容。因此,完成所有这些 *** 作后,只需修改
ModelAdmin的
list_display属性,例如:
class DataAdmin(admin.ModelAdmin): ... list_display = ('subject', 'get_current_year_sales', 'get_last_year_sales', 'get_current_quarter_sales', 'get_last_quarter_sales')
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)