django-rest-framework 如何处理多个 URL 参数?

Posted

技术标签:

【中文标题】django-rest-framework 如何处理多个 URL 参数?【英文标题】:django-rest-framework How to handle multiple URL parameter? 【发布时间】:2015-05-11 05:39:45 【问题描述】:

如何使用具有多个 URL 参数的通用视图?喜欢

GET /author/author_id/book/book_id

class Book(generics.RetrieveAPIView):

    queryset = Book.objects.all()
    serializer_class = BookSerializer
    lookup_field = 'book_id'
    lookup_url_kwarg = 'book_id'

    # lookup_field = 'author_id' for author
    # lookup_url_kwarg = 'author_id'

【问题讨论】:

【参考方案1】:

在这里聚会可能会迟到,但我就是这样做的:

class Book(generics.RetrieveAPIView):

    serializer_class = BookSerializer
    
    def get_queryset(self):
           book_id = self.kwargs['book_id']
           author_id = self.kwargs['author_id']     
           
           return Book.objects.filter(Book = book_id, Author = author_id)

【讨论】:

【参考方案2】:

加一点custom Mixin:

urls.py:

...

path('/author/<int:author_id>/book/<int:book_id>', views.Book.as_view()),

...

views.py: 改编自 DRF documentation 中的示例:

class MultipleFieldLookupMixin:
    def get_object(self):
        queryset = self.get_queryset()                          # Get the base queryset
        queryset = self.filter_queryset(queryset)               # Apply any filter backends
        multi_filter = field: self.kwargs[field] for field in self.lookup_fields
        obj = get_object_or_404(queryset, **multi_filter)       # Lookup the object
        self.check_object_permissions(self.request, obj)
        return obj


class Book(MultipleFieldLookupMixin, generics.RetrieveAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
    lookup_fields = ['author_id', 'book_id']    # possible thanks to custom Mixin

【讨论】:

【参考方案3】:

You'll need to use named groups in your URL structure 可能还有override the get() method of your view。

【讨论】:

以上是关于django-rest-framework 如何处理多个 URL 参数?的主要内容,如果未能解决你的问题,请参考以下文章

django-rest-framework:如何序列化已经包含 JSON 的字段?

如何在 django-rest-framework 中为 API 使用 TokenAuthentication

如何使用 django-rest-framework 进行社交登录? [关闭]

如何在 django-rest-framework 中对权限进行单元测试?

django-rest-framework:如何更新嵌套的外键?我的更新方法甚至没有被调用

如何仅使用 django 作为后端并使用 django-rest-framework 发布