首页 > 解决方案 > 如何在 html django 中引用外键

问题描述

{% for cred in allcreds %}
              {% if cred.datasource.name == '...' %}
              <h4>{{ cred.datasource }}</h4>
              {% endif %}
  {% endfor %}

在这种情况下,我检查条件中的数据源名称。然后它打印出数据源。我想有条件的数据源。

标签: djangodjango-modelsdjango-formsdjango-viewsdjango-templates

解决方案


我假设如果你打印出来{{ cred.protocoldatasource }}它不会输出任何东西,因为你的“关系”protocoldatasource不存在。

ProtocolUserCredentials您的模型具有的可用外键是: protocol, data_source, user, protocol_user

所以如果你这样做

{% if cred.data_source.name == 'Demonstration Protocol, ...' %}

或任何其他提到的关系,您可以访问您的相关模型。

另请注意,这{% if foo = 'bar' %}是无效的,您需要==在 if 语句中使用。


推荐阅读