简体   繁体   English

如何检查django模板中是否存在模型实例

[英]How to check if instance of model exists in django template

I have a django app with a basic model (Job). 我有一个带基本模型的django应用程序(Job)。 Now in my template I would like to check if an instance exists of that model or not. 现在在我的模板中,我想检查是否存在该模型的实例。 I want to project a text if there is nothing yet to show, otherwise I'd like to show the model attributes. 如果还没有显示,我想要投影文本,否则我想显示模型属性。

Somehow like so (which obviously doesn't work): 不知何故这样(显然不起作用):

{% if job.title != "" %}

{{ job.title }}

{% else %}

hola

{% endif %}

Also tried: 还尝试过:

 {% for job in jobs %}

      {% if job.title %}
      {{ job.title }}
      {% else %}
      Hola
      {% endif %}

  {% endfor %}

It makes sense it doesn't work because how can I loop through it or return something if it doesn't exist. 它是有道理的,它不起作用,因为我如何循环它或返回一些不存在的东西。 Is there a simple way to even do that in a template? 是否有一种简单的方法可以在模板中执行此操作? Or do I have to write my own function? 或者我必须编写自己的功能? Or what would be a way to do that? 或者这样做的方法是什么?

Help is of course very much appreciated 当然非常感谢帮助

You can use the {% if %} tag. 您可以使用{% if %}标记。 As Django doc says : 正如Django医生所说

The {% if %} tag evaluates a variable, and if that variable is “true” (ie exists, is not empty, and is not a false boolean value) the contents of the block are output. {% if %}标记计算变量,如果该变量为“true”(即存在,不为空,并且不是false布尔值),则输出块的内容。

So you can do something like this: 所以你可以这样做:

{% if job %}

{{ job.title }}

{% else %}

<p>Hi from Uruguay</p>

{% endif %}

If you need this inside a for, as @dirkgroten said, you need to use the {% empty %} tag. 如果你在for中需要这个,正如@dirkgroten所说,你需要使用{% empty %}标签。 There is an example in the Django doc. Django文档中有一个例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM