使用django过滤器,有没有一种快速的方法来支持所有可能的字段查找?

django-filter允许您轻松声明模型的可过滤字段。


例如


class UserFilter(django_filters.FilterSet):

    class Meta:

        model = User

        fields = ['username']

提供对字段的查找,该字段等效于此...exactusername


class UserFilter(django_filters.FilterSet):

    class Meta:

        model = User

        fields = {

            'username': ['exact']

        }

我正在寻找一种支持给定字段的所有可能的查找过滤器的方法,这样我就不必这样做:


class UserFilter(django_filters.FilterSet):

    class Meta:

        model = User

        fields = {

            "username": ["exact", "iexact", "contains", "icontains", "startswith", ..., etc.]

        }


千巷猫影
浏览 109回答 3
3回答

心有法竹

将 FilterSet 类的 get_fields(...) 类方法重写为,import django_filters as filters# If you are using DRF, import `filters` as# from django_filters import rest_framework as filtersclass AnyModelFilter(filters.FilterSet):    class Meta:        model = AnyModel        fields = '__all__'    @classmethod    def get_fields(cls):        fields = super().get_fields()        for field_name in fields.copy():            lookup_list = cls.Meta.model._meta.get_field(field_name).get_lookups().keys()            fields[field_name] = lookup_list        return fields

Cats萌萌

您可以通过django查找api获得字段的所有可能的查找lookups_list = []lookups = User._meta.get_field("username").get_lookups()for lookup in lookups:    lookups_list.append(lookup)lookups_list的结果:['exact', 'iexact', 'gt', 'gte', 'lt', 'lte', 'in', 'contains', 'icontains', 'startswith', 'istartswith', 'endswith', 'iendswith', 'range', 'isnull', 'regex', 'iregex']因此,您可以在FilterSet

呼唤远方

def fields_lookups(MyModel):&nbsp; &nbsp; lookups = {}&nbsp; &nbsp; fields = [x.name for x in MyModel._meta.fields] #<=1) get all fields names&nbsp; &nbsp; for field in fields:&nbsp; &nbsp; &nbsp; &nbsp; lookups[field] = [*MyModel._meta.get_field(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; field).get_lookups().keys()]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; #<=2) add each field to a `dict`and set it vlaue to the lookups&nbsp; &nbsp; return lookupsclass StatsticsView(ItemsView):&nbsp; &nbsp; queryset = MyModel.objects.all()&nbsp; &nbsp; serializer_class = StatisticSer&nbsp; &nbsp; filterset_fields = fields_lookups(MyModel) #<= ✅&nbsp; &nbsp; def get(self, request, *args, **kwargs):&nbsp; &nbsp; &nbsp; &nbsp; ....&nbsp; &nbsp; def put(self, request, *args, **kwargs):&nbsp; &nbsp; &nbsp; &nbsp; ....&nbsp; &nbsp; .&nbsp; &nbsp; .&nbsp; &nbsp; .
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python