在后端对查询集使用django-filters

ibps3vxo  于 2023-07-01  发布在  Go
关注(0)|答案(1)|浏览(154)

假设我有一个查询集和一些从前端获得的过滤器,我可以使用预定义的FilterSet来过滤查询集吗?示例:

models.py

class User(models.Model):
    name = models.CharField(...)
    score = models.IntegerField(...)

filters.py

class UserFilter(django_filters.FilterSet):
    q = django_filters.CharFilter(method="text_search_filter")
    score_min = django_filters.NumberFilter(field_name="score", lookup_expr="gte")
    score_max = django_filters.NumberFilter(field_name="score", lookup_expr="lte")

    class Meta:
        model = User
        fields = {}

    def text_search_filter(self, queryset, name, value):
        return queryset.filter(name__icontains=value)

views.py

class UserView(View):
    filter_class = UserFilter
    ...
    def post(self, request, **kwargs):
        qs = User.object.all()
        filters = {"q": "john doe", "score_min": 5, "score_max": 10}

我可以调用UserFilter并传递过滤器dict吗?以防止我再次应用这些过滤器,因为我已经在UserFilter中定义了这些过滤器
以下是我尝试过但没有成功的方法:

views.py

def post(self, request, **kwargs):
        qs = User.object.all()
        filters = {"q": "john doe", "score_min": 5, "score_max": 10}

        filter = UserFilter(request.GET, queryset=qs)
        filter.is_valid()
        qs = filter.filter_queryset(qs)  # Did not apply the filters
xesrikrc

xesrikrc1#

以下是对我有效的方法:
方法filter_queryset使用form.cleaned_data作为滤波器参数。当我调用它时,它没有初始化,因此没有应用过滤器。我使用源代码创建了自己的函数来接收过滤器参数。

def filter_queryset(filter_params, filterset, queryset):
    filters = filterset.filters
    for param, value in filter_params.items():
        ... # you might want to serialize some fields, like date (which is otherwise done under the hood to cleaned_data)

        queryset = filters[param].filter(queryset, value)
    return queryset.distinct()

相关问题