动态构造Q对象或NOP

时间:2019-03-01 19:31:07

标签: django django-rest-framework

我正在尝试根据传递的查询参数动态构造过滤器。下面的代码。 因为过滤器最终可能是空的,所以在这种情况下需要返回所有对象,所以这样做非常难看。

有没有办法做到这一点?也许是否有一个默认的Q表示“什么都不做”?

def get(self, request, *args, **kwargs):
    q = None
    for field, value in request.GET.items():
        if field not in Project._meta.fields:
            continue
        if q is None:
            q = Q(**{'{}'.format(field): value})
        else:
            q &= Q(**{'{}'.format(field): value})

    if q is None:
        projects = get_objects_for_user(request.user, ['api.view_project', 'api.edit_project', 'api.owner_project'], any_perm=True)
    else:
        projects = get_objects_for_user(request.user, ['api.view_project', 'api.edit_project', 'api.owner_project'], any_perm=True).filter(q)

    ser = ProjectSerializer(projects, many=True)

    return Response(ser.data, status=status.HTTP_200_OK)

2 个答案:

答案 0 :(得分:1)

Q()根本不会过滤掉任何东西。

答案 1 :(得分:0)

我建议使用django-filter

过滤器类别的示例:

import django_filters

class ProjectFilter(django_filters.FilterSet):

    class Meta:
        model = Product
        fields = [
            'id',
            'name',
            'user',
            'user__username',
        ]

查看功能示例:

def get(self, request, *args, **kwargs):
    projects = get_objects_for_user(request.user, ['api.view_project', 'api.edit_project', 'api.owner_project'], any_perm=True)

    projects = ProjectFilter(request.GET, queryset=projects)

    ser = ProjectSerializer(projects, many=True)

    return Response(ser.data, status=status.HTTP_200_OK)