在 Django 中创建模板时迭代模型属性 [英] Iterating over model attributes when creating a template in Django
问题描述
我在 Google App Engine 中使用 Django.如果我有课
I'm using Django in Google App Engine. If I have the class
class Person():
first_name = StringProperty()
last_name = StringProperty()
我有一个实例,其中 Person.first_name = Bob 和 Person.last_name = Vance,我可以创建一个模板来迭代 Person 属性以生成:
and I have an instance where Person.first_name = Bob and Person.last_name = Vance, can I create a template that iterates over the Person attributes to produce:
<tr>
<td>First</td>
<td>Bob</td>
</tr>
<tr>
<td>Last</td>
<td>Vance</td>
</tr>
也许更简洁,是否有一个 model.as_table() 方法可以打印出我的实例 Bob Vance 的属性?
Perhaps more succinctly, is there a model.as_table() method that will print out the attributes of my instance, Bob Vance?
推荐答案
在模板中,您无法访问 __underscored__ 属性或函数.我建议您在模型/类中创建一个函数:
In template you cannot access __underscored__ attributes or functions. I suggest instead you create a function in your model/class:
class Person(models.Model):
first_name = models.CharField(max_length=256)
last_name = models.CharField(max_length=256)
def attrs(self):
for attr, value in self.__dict__.iteritems():
yield attr, value
def sorted_attrs(self):
# Silly example of sorting
return [(key, self.__dict__[key]) for key in sorted(self.__dict__)]
在模板中它只是:
<tr>
{% for name, value in person.attrs %}
<td>{{name}}</td>
<td>{{value}}</td>
{% endfor %}
</tr>
现在这会给你first_name"而不是First",但你明白了.您可以将该方法扩展为 mixin,或者存在于父类中等.同样,如果您有几个想要迭代的人员对象,则可以使用它:
Now this will give you "first_name" instead of "First", but you get the idea. You can extend the method to be a mixin, or be present in a parent-class etc.. Similarly you can use this if you have a few person objects you want to iterate over:
{% for person in persons %}
<tr>
{% for name, value in person.attrs %}
<td>{{name}}</td>
<td>{{value}}</td>
{% endfor %}
</tr>
{% endfor %}
这篇关于在 Django 中创建模板时迭代模型属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!