如何在python中将方法添加到动态创建的类中?

from django.contrib import admin


from .filters import DropdownFilter


from django.db.models import Q


from django.utils.translation import gettext_lazy as  _


from .models import User



def queryset(self, request, queryset):

    term = self.value()

    if term is None:

        return

    term = term.lower

    username = Q()

    for bit in term.spilt():

        username = Q(username, queryset)

        return queryset.filter(username)



class InputFilter(admin.filters.SimpleListFilter):


   template = 'admin/input_filter.html'


   def lookups(self, request, model_admin):

      # Dummy, required to show the filter.

      return ((),)


   def choices(self, changelist):

      # Grab only the "all" option.

      all_choice = next(super().choices(changelist))

      all_choice['query_parts'] = ((k, v)for k, v in changelist.get_filters_params().items() if k != self.parameter_name)

      yield all_choice



class TransactionAdmin(admin.ModelAdmin):

    list_display = [field.name for field in User._meta.fields]

    c = type('UserFilter',(InputFilter,),{'title' : _('title'),'parameter_name' : 'search', 'query': queryset})

    c.queryset = queryset

    list_filter = [type('UserFilter',(InputFilter,),{'title' : _(i),'parameter_name' : i, 'query': queryset}) for i in list_display]


admin.site.register(User, TransactionAdmin)

代码是关于创建自定义文本输入过滤器到django管理站点,在这里我想将每个字段名称传递给标题,并将查询集函数添加到动态创建的类中,但似乎它不起作用,我得到了如下错误


  NotImplementedError at /admin/epic/user/


  subclasses of ListFilter must provide a queryset() method

如何解决这个问题?


不负相思意
浏览 120回答 2
2回答

偶然的你

你应该像queryset()一样用大括号调用函数。

红颜莎娜

list_filter = [type('UserFilter',(InputFilter,),{'title' : _(i),'parameter_name' : i, 'queryset': queryset}) for i in list_display]它现在正在工作。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python