如何为'django_filters.FilterSet'创建一个mixin?

ljo96ir5  于 2023-11-20  发布在  Go
关注(0)|答案(1)|浏览(129)

我有一堆FilterSet,我想添加相同的新过滤器,但每当我做下面的事情时,我得到一个错误,说FilterSet.Meta必须指定一个模型。例如:

class ModifiedAtMixin:
   modified_at_until = django_filters.DateTimeFilter(method="modified_until")

   def modified_until(self, queryset, name, value):
      return queryset.filter(modified_at__lte=value)

   class Meta:
      fields = ("modified_at_until",)
   

class FooFilterSet(ModifiedAtMixin, django_filters.rest_framework.FilterSet):
   created_at_until = django_filters.DateTimeFilter(method="created_until")

   def created_until(self, queryset, name, value):
      return queryset.filter(created_at__lte=value)

   class Meta:
      model = Foo
      fields = ModifiedAtMixin.Meta.fields + ("created_at_until",)

字符串
作为参考,我还尝试更改FooFilterSet中父类的顺序,但一无所获。
如何创建一个可重用的mixin,如ModifiedAtMixin

pvcm50d1

pvcm50d11#

不幸的是,FilterSet的设计是这样的,你必须应用一个黑客解决方案:

class ModifiedAtMixin:
    def __new__(cls, *args, **kwargs):
        new_obj = super().__new__(cls)
        filter_ = django_filters.DateTimeFilter(method="created_until", field_name="modified_at_until")
        new_obj.base_filters.update({"modified_at_until": filter_})
        return new_obj

   def modified_until(self, queryset, name, value):
      return queryset.filter(modified_at__lte=value)

字符串

相关问题