新手 - 了解 Django 基于 class 的视图动态过滤
newbie - understanding Django's class-based views dynamic filtering
我正在尝试关注并从文档中了解 Django 中的动态过滤。 https://docs.djangoproject.com/en/1.10/topics/class-based-views/generic-display/#dynamic-filtering
我一直在一步一步地跟进 copy/pasted 文档中的代码。但是我不明白关于将发布者添加到上下文中的最后一点,这意味着我无法弄清楚如何在模板中查询该数据。我唯一能得到一个 "hold" 的出版商。
因为在 PublisherDetail 视图中 publisher_detail.html
您只需像这样直接做一些事情,列出出版商的所有图书:
{% for book in book_list %}
{{ book.title }}
{% endfor %}
这是让我绊倒的部分。
We can also add the publisher into the context at the same time, so we
can use it in the template:
# ...
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super(PublisherBookList, self).get_context_data(**kwargs)
# Add in the publisher
context['publisher'] = self.publisher
return context
您可以按照此处所述访问相关对象:What is `related_name` used for in Django?。
尝试调用 publisher.books.all()
或 publisher.book_set.all()
:
{% for book in publiser.book_set.all %}
{{ book.title }}
{% endfor %}
在get_context_data
中设置context['publisher'] = self.publisher
意味着您可以在上下文中显示发布者的详细信息。例如,您可以在书名列表上方显示出版商名称:
<h2>Books published by {{ publisher.name }}</h2>
{% for book in book_list %}
{{ book.title }}
{% endfor %}
我正在尝试关注并从文档中了解 Django 中的动态过滤。 https://docs.djangoproject.com/en/1.10/topics/class-based-views/generic-display/#dynamic-filtering 我一直在一步一步地跟进 copy/pasted 文档中的代码。但是我不明白关于将发布者添加到上下文中的最后一点,这意味着我无法弄清楚如何在模板中查询该数据。我唯一能得到一个 "hold" 的出版商。
因为在 PublisherDetail 视图中 publisher_detail.html
您只需像这样直接做一些事情,列出出版商的所有图书:
{% for book in book_list %}
{{ book.title }}
{% endfor %}
这是让我绊倒的部分。
We can also add the publisher into the context at the same time, so we can use it in the template:
# ...
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super(PublisherBookList, self).get_context_data(**kwargs)
# Add in the publisher
context['publisher'] = self.publisher
return context
您可以按照此处所述访问相关对象:What is `related_name` used for in Django?。
尝试调用 publisher.books.all()
或 publisher.book_set.all()
:
{% for book in publiser.book_set.all %}
{{ book.title }}
{% endfor %}
在get_context_data
中设置context['publisher'] = self.publisher
意味着您可以在上下文中显示发布者的详细信息。例如,您可以在书名列表上方显示出版商名称:
<h2>Books published by {{ publisher.name }}</h2>
{% for book in book_list %}
{{ book.title }}
{% endfor %}