将Django Queryset转换为模板中的列表?

huangapple go评论52阅读模式
英文:

How to convert Django Queryset into a list in template?

问题

以下是已翻译的代码部分:

class Building(models.Model):
    Building_code = models.CharField(primary_key=True, max_length=255)
    Building_name = models.CharField(max_length=255)

    @property
    def BuildingFullName(self):
        fullname = '{} | {}'.format(self.Building_code, self.Building_name)
        return fullname

    def __str__(self):
        return self.Building_code
<tbody>
{% for hira in hiras %}
    <tr>
         <td>{{ hira.Activity }}</td>
         <td>{{ hira.Hazard.Hazard }}</td>
         <td>{{ hira.PBS.Code }}</td>
         {% with allbuilding=hira.Building.all %}
             <td>{{ allbuilding }}</td>
         {% endwith %}
         <td>{{ hira.Building.Function_Mode }}</td>
{% endfor %}
</tbody>

希望这可以帮助你解决问题。如果你需要进一步的帮助,请告诉我。

英文:

Here is my model :

class Building(models.Model):
    Building_code = models.CharField(primary_key=True, max_length=255)
    Building_name = models.CharField(max_length=255)

    @property
    def BuildingFullName(self):
        fullname = &#39;{} | {}&#39;.format(self.Building_code, self.Building_name)
        return fullname

    def __str__(self):
        return self.Building_code

What i do in my template :

&lt;tbody&gt;
{% for hira in hiras %}
    &lt;tr&gt;
         &lt;td&gt;{{ hira.Activity }}&lt;/td&gt;
         &lt;td&gt;{{ hira.Hazard.Hazard }}&lt;/td&gt;
         &lt;td&gt;{{ hira.PBS.Code }}&lt;/td&gt;
         {% with allbuilding=hira.Building.all %}
             &lt;td&gt;{{ allbuilding }}&lt;/td&gt;
         {% endwith %}
         &lt;td&gt;{{ hira.Building.Function_Mode }}&lt;/td&gt;
{% endfor %}
&lt;/tbody&gt;

This is what I am getting :
将Django Queryset转换为模板中的列表?

But I would like the building list to be displayed without this "<Queryset". For the first row, it would be "13, 14".

答案1

得分: 1

你可以使用 join:

{% with allbuilding=hira.Building.all %}
     &lt;td&gt;{{ allbuilding|join:&quot;, &quot;  }}&lt;/td&gt;
{% endwith %}
英文:

You can use join:

{% with allbuilding=hira.Building.all %}
     &lt;td&gt;{{ allbuilding|join:&quot;, &quot;  }}&lt;/td&gt;
{% endwith %}

huangapple
  • 本文由 发表于 2023年4月17日 15:52:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76032838.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定