Django:如果数据库中存在值,则将其作为变量从视图传递到模板

Django: If value exists in database, pass it as a variable from view to template

我是编码新手,也是 Django 新手。我在 Whosebug 上搜索了我的问题,但没有找到我要找的内容:

我想做的是检查某些值是否在我的数据库中,如果是,则将其作为变量传递给模板。这些值将是下拉菜单的项目。 例如,如果我有一个包含 bicycle1 到 bicycleN 的数据库,我想检查每个数据库对象的属性“handlebar”的值是否与某个制造商匹配。如果是,将其传递给模板,以便它可以出现在下拉菜单中,以便稍后过滤结果。

首先我想我应该检查模板本身并考虑这样的事情:

bicyle_list.html

  <ul id='dropdown1' class='dropdown-content'>
      {% for bicyle in bicycles %}
          {% with manufacturerA=False %}
            {% if manufacturerA == False and bicycle.handlebar == "manufacturerA" %}
                <li><a href="#!">ManufacturerA</a></li>
                {% manufacturerA=True %}
            {% endif %}
          {% endwith %}
      {% endfor %}

但据我了解,模板应该只包含呈现逻辑。 (此外,我必须在 for 循环中使用布尔变量,因为制造商应该只在下拉菜单中出现一次,即使有几辆自行车带有特定的车把。更改模板中的变量值似乎很复杂对我来说。)

在 views.py 中,我考虑过这个,但不知道如何处理条件和渲染方法:

views.py

        bicycles = Bicycle.objects.all()
        for bicycle in bicyles:
           if bicycle.handlebar == "manufacturerA":
               manufacturerA= "manufacturerA"
           if bicycle.handlebar == "manufacturerB":
               manufacturerB= "manufacturerB"

#if variable manufacturerA exists, pass it to the template – if not, not! Same with manufacturerB
#But how to include in return render(..)?

        return render(request, 'shop/bicycle_list.html', {'bicycles': bicycles}) 

你知道如何传递可选变量吗?

您可以获得不同制造商的列表:

def some_view(request):
    manufacturers = Bicycle.objects.values_list('handlebar', flat=True).distinct()
    return render(request, 'shop/bicycle_list.html', {'manufacturers': manufacturers})
<ul id='dropdown1' class='dropdown-content'>
  {% for <b>manufacturer in manufacturers</b> %}
    <li><a href="#!">{{ manufacturer }}</a></li>
  {% endfor %}
</ul>

然而,您可能想为制造商制作模型,并使用 many-to-one relationship [Django-doc]