如何在Django中以正确的方式使用get_queryset?

时间:2015-03-31 10:49:59

标签: django django-rest-framework

我尝试使用django中的def_queryset为django-rest-framework视图编写过滤器。我有一个列表视图,我希望能够使用4个不同的字段进行过滤 - 无论是单独还是同时。这有15种不同的组合(4个单元素,6个双元素,4个3元素和1个4元素)。可能有一种更聪明的方式来编写那些而不是大的其他语句,如下所示:

def get_queryset(self):
    queryset = Comment.objects.filter(status=1)
    post = self.request.QUERY_PARAMS.get('post', None)
    parent = self.request.QUERY_PARAMS.get('parent', None)
    author = self.request.QUERY_PARAMS.get('author', None)
    email = self.request.QUERY_PARAMS.get('author', None)

    # this is obviously incomplete

    if post is not None and parent is not None and author is not None and email is not None:
        queryset = queryset.filter(post=post, parent=parent, author=author, email=email)
    elif post is not None and parent is not None and author is not None:
        queryset = queryset.filter(post=post, parent=parent, author=author)
    elif post is not None and parent is not None and email is not None:
        queryset = queryset.filter(post=post, parent=parent, email=email)
    elif parent is not None and author is not None and email is not None:
        queryset = queryset.filter(parent=parent, author=author, email=email)

    return queryset

我不想使用其他库,例如django-filters。任何有关如何编写这些更简单并可能在不同视图中重用的想法都将非常受欢迎。

1 个答案:

答案 0 :(得分:2)

您可以链接filter次来电(正如您在第一次通话后所做的那样):

if post is not None:
    queryset = queryset.filter(post=post)
if parent is not None:
    queryset = queryset.filter(parent=parent)
...

请注意if而不是elif