如何在 Django 中正确使用 get_queryset?

How to use get_queryset the right way in Django?

我正在尝试使用 django 中的 def_queryset 为 django-rest-framework 视图编写过滤器。我有一个列表视图,我希望能够使用 4 个不同的字段进行过滤 - 单独或同时进行。这是 15 种不同的组合(4 种单元素、6 种二元素、4 种三元素和 1 种四元素)。可能有一种更聪明的方法来编写这些而不是大的 else 语句,如下所示:

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。任何关于如何编写更简单且可能跨不同视图重用的想法都将不胜感激。

您可以链接 filter 个调用(正如您在第一次调用后所做的那样):

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

请注意 if 而不是 elif