6

How can I use generic views with multiple URL parameters? Like

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'

3 Answers 3

4

Just add a little custom Mixin:

in urls.py:

...

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

...

in views.py: Adapted from example in the 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
Sign up to request clarification or add additional context in comments.

Comments

3

Might be late to the party here, but this is what I do:

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)

Comments

1

You'll need to use named groups in your URL structure and possibly override the get() method of your view.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.