繁体   English   中英

如何向python中动态创建的类添加方法?

[英]How to add methods to the dynamically created classes in 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

如何解决这个问题呢?

你应该用大括号调用函数,比如 queryset()。

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

它现在正在工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM