django - 获取 django 模板中的相关字段
问题描述
我有两个模型:
class Button(models.Model):
title = models.CharField(max_length=100,)
anchor = models.ForeignKey(Section, on_delete=models.CASCADE,
related_name='anchor', blank=True, null=True,)
class Section(models.Model):
...
transliterate_name = models.CharField(max_length=100, blank=True,
null=True)
现在我想在我的模板中获取 transliterate_name 。我将此字段用作文章的 id。我想将它分配给导航菜单中的按钮 ID。有我的模板:
<ul class="navbar-nav">
{% for menu_btn in menu_buttons %}
<li class="nav-item">
<a href="#{{ ??? }}" class="nav-link">
{{ menu_btn.title }}
</a>
</li>
{% endfor %}
</ul>
在我看来:
class SectionView(ListView):
queryset = Section.objects.filter(name_visible=True)
context_object_name = 'sections'
extra_context = {
'articles': Article.objects.all(),
'menu_buttons': Buttons.objects.all(),
}
template_name = 'sections/sections.html'
请有任何建议。
解决方案
您可以通过获取属性来获取相关Section
对象:anchor
<a href="#{{ menu_btn.anchor.transliterate_name }}" class="nav-link">
由于您将获取每个 Button
对象的相关属性,因此最好在一次获取中获取所有这些Section
s :.select_related(..)
class SectionView(ListView):
queryset = Section.objects.filter(name_visible=True)
context_object_name = 'sections'
extra_context = {
'articles': Article.objects.all(),
'menu_buttons': Buttons.objects.select_related('anchor').all(),
}
template_name = 'sections/sections.html'
推荐阅读
- c++ - 我无法使用 SFML 库打开和图像
- magento2 - Magento 2 更改基本 URL 会中断页面
- wordpress - WC_Product_Query 不适用于 have_posts()
- flutter - gradle中的问题
- sql - 连接表 - 仅显示左表的每一行一次,并添加一行包含未连接到表的数据
- c# - 如何使用 Botframework v4 在 Messenger 上获取持久菜单和开始按钮?
- matplotlib - imshow 和 pick_event 是否适用?
- video - 减少压缩伪影(使用 madVR 作为 ffmpeg 的过滤器?)
- python - Python:提取两个节号之间的段落
- python - 如何将多个输入解析为字典?