python - Create a custom function as a filter in proxy model, django admin
问题描述
I need help to convert CashInhandAdmin->expense as a filter (high and low), have tried below filter but failed because proxy model is inherited from user_profile model but want to filter expense sum that is different model.
Filter
class ExpenseFilter(admin.SimpleListFilter):
title = 'Expense'
parameter_name = 'Expense'
def lookups(self, request, model_admin):
"""
Returns a list of tuples. The first element in each
tuple is the coded value for the option that will
appear in the URL query. The second element is the
human-readable name for the option that will appear
in the right sidebar.
"""
return (("low", "Filter by low amount"), ("high", "Filter by high amount"))
def queryset(self, request, queryset):
"""
Returns the filtered queryset based on the value
provided in the query string and retrievable via
`self.value()`.
"""
if self.value() == "low_price":
return queryset.order_by("expense")
elif self.value() == "high_price":
return queryset.order_by("-expense")
else:
return queryset.all()
Model
class CashInhand(user_profile):
class Meta:
proxy = True
verbose_name = "Cash In Hand"
verbose_name_plural = "Cash In Hand"
Admin
class CashInhandAdmin(admin.ModelAdmin, admin.SimpleListFilter):
def get_queryset(self, request):
print(request.GET.get("Expense"))
qs = super(CashInhandAdmin, self).get_queryset(request)
return qs.filter(employee__isnull=False).distinct("employee_id").order_by("employee_id")
def has_delete_permission(self, request, obj=None):
return False
def expense(obj):
exp = models.Expense.objects.filter(created_by_id=obj.employee, status='1').annotate(
as_float=Cast('amount', FloatField())).aggregate(Sum("as_float"))
if exp["as_float__sum"]:
return int(math.ceil(exp["as_float__sum"]))
else:
return str(0)
list_display = (expense,)
list_filter = (ExpenseFilter)
解决方案
推荐阅读
- asp.net-core - Azure Pipelines:迁移到 .NET Core 3.1 后,Dotnet 发布失败,退出代码为 1
- docker - 升级到 ChromeDriver v80 和 Chrome v80 后,Chrome 无法在使用 Selenium 的 docker 容器中启动
- image - 如何有效地将图像作为 pubspec.yaml 中的资产处理?
- c# - Asp.Net - 使用 IHostedService 的计划任务
- flutter - Flutter 更改 Drawer UserAccountsDrawerHeader 布局
- php - Dockerizing Drupal 8 on AWS ECS 错误:Drupal 目标组中的任务失败 ELB 健康检查
- spring - 运行测试时跳过 JPA 生命周期方法
- jquery - JQuery async .each 返回空承诺
- ios - AVAssetWriter 最后一帧的长度
- php - 如何在typo3 v9 中使用PHP 脚本?