在Django中创建模板时迭代模型属性 [英] Iterating over model attributes when creating a template in Django
问题描述
class Person():
first_name = StringProperty()
last_name = StringProperty ()
我有一个实例,其中Person.first_name = Bob和Person.last_name = Vance,can我创建一个模板,迭代Person属性以产生:
< tr>
< td>首先< / td>
< td> Bob< / td>
< / tr>
< tr>
< td> Last< / td>
< td> Vance< / td>
< / tr>
也许更简洁,有一个model.as_table()方法,将打印出我的属性实例Bob Vance?
在模板中,您无法访问__underscored__属性或函数。
我建议你在你的模型/类中创建一个函数:
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):
#排序的愚蠢例子
return [(key,self。 __dict __ [key])用于排序(self .__ dict__)中的键)
在模板中只是: / p>
< tr>
{%for name,value in person.attrs%}
< td> {{name}}< / td>
< td> {{value}}< / td>
{%endfor%}
< / tr>
现在这将给你first_name而不是First,但是你会得到想法。您可以将该方法扩展为一个mixin,或者存在于父类中。
同样,如果您要迭代几个对象,可以使用此方法:
{%for person in persons%}
< tr>
{%for name,value in person.attrs%}
< td> {{name}}< / td>
< td> {{value}}< / td>
{%endfor%}
< / tr>
{%endfor%}
I'm using Django in Google App Engine. If I have the class
class Person():
first_name = StringProperty()
last_name = StringProperty()
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>
Perhaps more succinctly, is there a model.as_table() method that will print out the attributes of my instance, Bob Vance?
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__)]
In template it's just:
<tr>
{% for name, value in person.attrs %}
<td>{{name}}</td>
<td>{{value}}</td>
{% endfor %}
</tr>
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屋!