如何使用具有多个网址参数的通用视图?像
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'
答案 0 :(得分:2)
答案 1 :(得分: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