我正在尝试编写一个简单的 Django View ,该 View 打印出一个表示模型中所有字段的表。
我有一个名为 Menu_Items 的模型,有 6 个字段:
Item_Id
Name
Description
Base_Price
Image_Path
Item_Tags
使用Menu_Items._meta.fields
我可以检索字段列表。
对于给定的查询集(例如Menu_Items.objects.all()
),我想打印出所有字段,并格式化为表格。
我尝试在上下文中传递字段,但我无法弄清楚要使用哪个模板标记。是否可以在模板标签内使用模板标签?像这样:
{% for field in fields %}
{{ menuItems.0.{{ field.name }} }}
{{ field.name }}
{% endfor %}
在本例中,该字段是 Menu_Items._meta.fields 返回的每个字段
最佳答案
不要这样做,而是更改您的查询,使其返回带有 values()
的 ValueQuerySet
.
您的结果将是一个字典列表,以下是文档中的示例:
>>> Blog.objects.filter(name__startswith='Beatles').values()
[{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}]
现在,在您的模板中:
{% for item in results %}
{% for column,value in item.iteritems %}
{{ column }} {{ value }}
{% endfor %}
{% endfor %}
这将导致:
id 1
name Beatles Blog
tagline All the latest Beatles news.
关于python - Django – 在模板标签中使用模板标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21899350/