有没有一种方法可以使Django模板变量变为for循环

时间:2020-10-08 13:29:34

标签: django django-templates

我的模型中有这个

tank0 = models.ForeignKey(nb200V1, on_delete=models.SET_NULL, null=True, blank=True, related_name='pmp300Tank0')
tank0MQTT = models.BooleanField(default = False)
tank1 = models.ForeignKey(nb200V1, on_delete=models.SET_NULL, null=True, blank=True, related_name='pmp300Tank1')
tank1MQTT = models.BooleanField(default = False)
tank2 = models.ForeignKey(nb200V1, on_delete=models.SET_NULL, null=True, blank=True, related_name='pmp300Tank2')
tank2MQTT = models.BooleanField(default = False)
tank3 = models.ForeignKey(nb200V1, on_delete=models.SET_NULL, null=True, blank=True, related_name='pmp300Tank3')
tank3MQTT = models.BooleanField(default = False)
tank4 = models.ForeignKey(nb200V1, on_delete=models.SET_NULL, null=True, blank=True, related_name='pmp300Tank4')
tank4MQTT = models.BooleanField(default = False)
tank5 = models.ForeignKey(nb200V1, on_delete=models.SET_NULL, null=True, blank=True, related_name='pmp300Tank5')
tank5MQTT = models.BooleanField(default = False)
tank6 = models.ForeignKey(nb200V1, on_delete=models.SET_NULL, null=True, blank=True, related_name='pmp300Tank6')
tank6MQTT = models.BooleanField(default = False)

我希望在模板中创建一个for循环以生成html,并在for循环中使用i设置变量,如下所示:

{% for i in "0123456" %}
<div class="row" style="margin-top:10px">
    <div class="col-sm-12">
        <div class="card">
            <div class="card-header">
                Tank # {{forloop.counter}}
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-lg-2 col-md-3 col-sm-4 align-self-center">
                        <label><b>Serial:</b></label>
                        <a href="#" id="{{obj.serial}}_tank{{i}}">{{obj.tank{{i}}.serial}}</a>
                        <small id="{{obj.tank{{i}}.serial}}_serial_ts" class="form-text text-muted">{{obj.tank{{i}}.timeStamp}}</small>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

{%endfor%}

有什么办法做到这一点吗?

1 个答案:

答案 0 :(得分:0)

我同意w @ Willem,您应该使用反向外键。

但是如果您保留该模型结构,那么添加一个返回字段列表的模型属性呢?

@property
def tank_list(self):
   return [
     (getattr(self, f"tank{i}"), getattr(self, f"tank{i}MQTT")
     for i in range(7)
   ]

然后,您可以在模板中循环浏览该列表。要从每个元组中获得第0,第1个元素,只需执行以下操作:

{% for tank_fields in obj.tank_list %}
  {{ tank_fields.0 }}
  {{ tank_fields.1 }}
{% endfor %}