【问题标题】:How to use a property method in list_filter in custom admin changelist?如何在自定义管理更改列表中使用 list_filter 中的属性方法?
【发布时间】:2020-07-17 03:43:48
【问题描述】:

我有一个这样的模型:

class CustomUser(AbstractUser):
    @property
    def is_paid(self):
        return self.apayment4thisuser.all().filter(expirydate__gt=timezone.now().date()).count()>0

在 customadmin 中,我可以在 list_display 中添加 is_paid,但是当我将其添加到我的 list_filter 时会引发错误:

class CustomUserAdmin(UserAdmin):
    model = CustomUser
    list_filter = ['app_user','is_paid']
    list_display = ['id',
                    'username',
                    'email',
                    'is_paid',
                    ]

这是错误:

ERRORS:
<class 'users.admin.CustomUserAdmin'>: (admin.E116) The value of 'list_filter[1]' refers to 'is_paid', which does not refer to a Field.

有没有办法将此添加到list_filter?

【问题讨论】:

  • 你需要为你想要的创建一个自定义过滤器,它应该是一个继承自SimpleListFilter的类。文档中有一段关于如何做到这一点docs.djangoproject.com/en/3.0/ref/contrib/admin/…
  • This 应该有帮助
  • @Iain Shelvington ,我试过了,但它看起来也适用于田野,它在财产上失败了。它给出了一个错误“无法将关键字'is_paid'解析为字段”
  • 过滤机制发生在数据库级别,因此您不能对属性执行此操作,除非您创建了带注释的字段。

标签: django django-models


【解决方案1】:

使用这样的自定义过滤器:

class IsPaidFilter(SimpleListFilter):

   # Human-readable title which will be displayed in the
   # right admin sidebar just above the filter options.
   title = 'is paid'

   # Parameter for the filter that will be used in the URL query.
   parameter_name = 'is_paid'

   def lookups(self, request, model_admin):
      return (
           ('True', True), 
           ('False', False)
             )

   def queryset(self, request, queryset): 
      if self.value():
          # If is_paid=True filter is activated
          return queryset.filter(<Write your logic here>)
      else:
          # If is_paid=True filter is activated
          return queryset.filter(<Write your other logic>)

对于这个逻辑,这可能很有用:

Q(Count(apayment4thisuser, 
      filter=Q(apayment4thisuser__expirydate__gt=timezone.now().date())))

【讨论】:

    猜你喜欢
    • 2011-10-08
    • 2017-06-15
    • 1970-01-01
    • 1970-01-01
    • 2019-05-08
    • 1970-01-01
    • 1970-01-01
    • 2016-12-11
    • 2012-03-23
    相关资源
    最近更新 更多