使用Django Rest Framework我有一个过滤器Mixin。您可以过滤当前用户或项目ID,但不能同时过滤这两者。如何将这些查询链接在一起,以便您可以同时对这两个查询进行过滤?
class FilterMixin(object):
"""
Applies a set of filters for Lists API calls.
"""
def get_queryset(self, *args, **kwargs):
"""
Checks if currentuser = true is in the URL and filters this it.
"""
currentuser = self.request.QUERY_PARAMS.get('currentuser', False)
if currentuser == "true":
return super(FilterMixin, self).get_queryset(*args, **kwargs).filter(user=self.request.user)
project = self.request.QUERY_PARAMS.get('project', False)
if project:
return super(FilterMixin, self).get_queryset(*args, **kwargs).filter(project=project)
return super(FilterMixin, self).get_queryset(*args, **kwargs)
我可以为每个过滤器创建一个新的Mixin,并使用可行的Super(),但我想避免这种情况。
答案 0 :(得分:2)
这里你去......
def get_queryset(self, *args, **kwargs):
"""
Checks if currentuser = true is in the URL and filters this it.
"""
queryset = super(FilterMixin, self).get_queryset(*args, **kwargs)
currentuser = self.request.QUERY_PARAMS.get('currentuser')
project = self.request.QUERY_PARAMS.get('project')
if currentuser == "true":
queryset = queryset.filter(user=self.request.user)
if project:
queryset = queryset.filter(project=project)
return queryset