首页 > 解决方案 > 获取 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'

请有任何建议。

标签: django

解决方案


您可以通过获取属性来获取相关Section对象:anchor

<a href="#{{ menu_btn.anchor.transliterate_name }}" class="nav-link">

由于您将获取每个 Button对象的相关属性,因此最好在一次获取中获取所有这些Sections :.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'

推荐阅读