【发布时间】:2021-01-18 07:46:45
【问题描述】:
我正在构建一个library Django 应用程序,其中我有一个BooksView 来显示某个Author 编写的所有Books。在某些情况下,我希望在查询集中的所有其他书籍之前显示一个 Book。这应该在图书的 id 出现在 URL 中时发生,否则,所有图书都应按时间顺序列出。
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)
我怎样才能完成我的TODO?如何将对象推送到现有查询集的前面?
【问题讨论】:
-
您能检查一下在数据库中创建的模式吗?它在您的列上有唯一索引吗?类似于 table(lower(col_name));
标签: python django django-models django-views django-queryset