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

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

How to convert Django Queryset into a list in template?

问题

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

  1. class Building(models.Model):
  2. Building_code = models.CharField(primary_key=True, max_length=255)
  3. Building_name = models.CharField(max_length=255)
  4. @property
  5. def BuildingFullName(self):
  6. fullname = '{} | {}'.format(self.Building_code, self.Building_name)
  7. return fullname
  8. def __str__(self):
  9. return self.Building_code
  1. <tbody>
  2. {% for hira in hiras %}
  3. <tr>
  4. <td>{{ hira.Activity }}</td>
  5. <td>{{ hira.Hazard.Hazard }}</td>
  6. <td>{{ hira.PBS.Code }}</td>
  7. {% with allbuilding=hira.Building.all %}
  8. <td>{{ allbuilding }}</td>
  9. {% endwith %}
  10. <td>{{ hira.Building.Function_Mode }}</td>
  11. {% endfor %}
  12. </tbody>

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

英文:

Here is my model :

  1. class Building(models.Model):
  2. Building_code = models.CharField(primary_key=True, max_length=255)
  3. Building_name = models.CharField(max_length=255)
  4. @property
  5. def BuildingFullName(self):
  6. fullname = &#39;{} | {}&#39;.format(self.Building_code, self.Building_name)
  7. return fullname
  8. def __str__(self):
  9. return self.Building_code

What i do in my template :

  1. &lt;tbody&gt;
  2. {% for hira in hiras %}
  3. &lt;tr&gt;
  4. &lt;td&gt;{{ hira.Activity }}&lt;/td&gt;
  5. &lt;td&gt;{{ hira.Hazard.Hazard }}&lt;/td&gt;
  6. &lt;td&gt;{{ hira.PBS.Code }}&lt;/td&gt;
  7. {% with allbuilding=hira.Building.all %}
  8. &lt;td&gt;{{ allbuilding }}&lt;/td&gt;
  9. {% endwith %}
  10. &lt;td&gt;{{ hira.Building.Function_Mode }}&lt;/td&gt;
  11. {% endfor %}
  12. &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:

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

You can use join:

  1. {% with allbuilding=hira.Building.all %}
  2. &lt;td&gt;{{ allbuilding|join:&quot;, &quot; }}&lt;/td&gt;
  3. {% 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:

确定