我是django的新手,最近阅读了一篇介绍基于类的视图用法的教程。但是,当我尝试将2个不同的查询集(所有数据和已过滤的数据)呈现到同一模板时,我找不到显示2个不同的查询集的解决方案。谁能建议最好的解决方案?
我知道编写基于函数的视图非常容易,但是我希望可以通过基于类的视图来完成,谢谢
#in view.py
from django.views.generic import ListView
from books.models import Book
class BookListView(generic.ListView):
model = Book
context_object_name = 'my_book_list'
queryset = Book.objects.all()
template_name = 'books/my_arbitrary_template_name_list.html'
# queryset = Book.objects.filter(title='war')?
#in templage.py
#Main content
<div class="main_content">
<h1>All War</h1>
<ul>
{% for book in book_list %}
<li>
{{book.title}}
</li>
{% for endfor %}
</ul>
</div>
#Sidebar
<div class="sidebar">
<h1>All War</h1>
<ul>
{% for book in book_list %}
<li>
{{book.title}}
</li>
{% for endfor %}
</ul>
</div>
答案 0 :(得分:0)
您应该查看 get_context_data 以添加所需的其他查询。
视图可能看起来像这样
class BookListView(generic.ListView):
model = Book
context_object_name = 'my_book_list'
queryset = Book.objects.all()
template_name = 'books/my_arbitrary_template_name_list.html'
def get_context_data(self, **kwargs):
context = super(BookListView, self).get_context_data(**kwargs)
context['second_queryset'] = # YOUR QUERY HERE
return context
在此示例中,第二个查询为 second_queryset ,可以在html模板中以 {{second_queryset}} 进行访问。如果您对更多查询执行相同操作,则可以添加更多内容。
def get_context_data(self, **kwargs):
context = super(BookListView, self).get_context_data(**kwargs)
context['second_queryset'] = # YOUR QUERY HERE
context['third_queryset'] = # YOUR QUERY HERE
...
return context
您可以在here中了解更多信息。