Saturday 24 October 2020

Django - Add object in front of existing QuerySet

I am building a library Django application where I have a BooksView to display all Books written by a certain Author. Under certain conditions, I want a single Book to be displayed before all other books in the query set. This should happen when the id of the book appears in the URL, otherwise, all books should be listed in chronological order.

books/urls.py:

urlpatterns = [

    # Books displayed in chronological order
    path("<slug:author>/books", views.BooksView.as_view()),

    # Books displayed in chronological order
    # but first book is the one with id `book`
    path("<slug:author>/books/<int:book>", views.BooksView.as_view()),
]

books/views.py:

class BooksView(APIView):

    def get(self, request, author, book=None):

        author = get_object_or_404(Author, slug=author)
        books = author.author_books
        books = books.order_by("-pub_date")

        if book:
            book = get_object_or_404(Book, id=book)
            # TODO: add `book` in front of books QuerySet (and remove duplicated if any)

        serializer = BooksSerializer(books, many=True)
        return Response(serializer.data)

How can I accomplish my TODO? How can I push an object in front of an existing query set?



from Django - Add object in front of existing QuerySet

No comments:

Post a Comment