0
我正嘗試使用django的def_queryset
爲django-rest-framework視圖編寫過濾器。我有一個列表視圖,我希望能夠使用4個不同的字段進行過濾 - 分別或同時進行。這是15種不同的組合(4個單元素,6個雙元素,4個三元素和1個四元素)。有可能是寫的,而不是大else語句,如下面的一個更聰明的辦法:如何在Django中以正確的方式使用get_queryset?
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的過濾器。任何想法如何寫這些簡單和可能重用不同的意見將非常讚賞。