【问题标题】:DRF ViewSet - dealing with query paramsDRF ViewSet - 处理查询参数
【发布时间】:2021-07-20 23:10:18
【问题描述】:

我想根据查询参数更改 ViewSet 中的查询集。 我看到查询参数中有一个标签列表,但是当我尝试提取它们时,我只得到最后一个标签作为字符串。而且我不知道它为什么以及如何工作。有人可以帮我解释一下吗?

class RecipeViewSet(ModelViewSet):
    pagination_class = PageNumberPagination
    permission_classes = [IsAuthenticatedOrReadOnly, IsAuthorOrReadOnly]

def get_serializer_class(self):
    if self.action in ['list', 'retrieve']:
        return RecipeListSerializer
    return RecipeCreateSerializer

def get_queryset(self):
    queryset = Recipe.objects.all()

    params = self.request.query_params
    tags = params.get("tags")
    print("params:")
    print(params) # <QueryDict: {'page': ['1'], 'limit': ['6'], 'tags': ['breakfast', 'lunch', 'dinner']}>
    print("tags:")
    print(type(tags)) # <class 'str'>
    print(tags) # I get only str - "dinner"
    if tags:
        queryset = Recipe.objects.filter(tags__slug__in=tags).distinct()
    return queryset

【问题讨论】:

    标签: django-rest-framework django-rest-viewsets drf-queryset


    【解决方案1】:

    要获取列表,您需要使用getlist。在您的情况下,它看起来像这样:

    params.getlist("tags[]")
    

    这是因为您使用的是 QueryDict 类型的实例,而不是 dict。您可以找到更多信息here

    【讨论】:

    • 太棒了!非常感谢!
    猜你喜欢
    • 2021-08-07
    • 1970-01-01
    • 1970-01-01
    • 2019-01-21
    • 1970-01-01
    • 2017-08-23
    • 2021-06-27
    • 2017-06-22
    • 2021-07-29
    相关资源
    最近更新 更多