迭代 Django 模板中的 Expando 动态属性
我正在尝试迭代 Expando-Model 的动态属性,以便将它们全部输出。除了创建自己的方法之外,还有其他方法可以做到这一点吗:
class Event(db.Expando):
platform = db.ReferenceProperty(Platform)
date = db.DateTimeProperty()
def getValues(self):
return self._dynamic_properties
然后在模板中 - 传递一个“平台”对象:
{% for event in platform.event_set %}
<b>{{ event.date }}</b><br />
{% for pair in event.getValues.items %}
{{ pair.0 }} = {{ pair.1 }}<br />
{% endfor %}
{% endfor %}
这可行,但我很惊讶我不能这样做:
{% for event in platform.event_set %}
<b>{{ event.date }}</b><br />
{% for pair in event.items %}
{{ pair.0 }} = {{ pair.1 }}<br />
{% endfor %}
{% endfor %}
没有我自己的方法方法调用...我应该使用“.items”以外的其他内容吗?
I'm trying to iterate through an Expando-Model's dynamic properties in order to output them all. Is there a way of doing this other than creating your own method like such:
class Event(db.Expando):
platform = db.ReferenceProperty(Platform)
date = db.DateTimeProperty()
def getValues(self):
return self._dynamic_properties
And then in the template - which is passed a 'platform' object:
{% for event in platform.event_set %}
<b>{{ event.date }}</b><br />
{% for pair in event.getValues.items %}
{{ pair.0 }} = {{ pair.1 }}<br />
{% endfor %}
{% endfor %}
This works, but I'm suprised I can't just do:
{% for event in platform.event_set %}
<b>{{ event.date }}</b><br />
{% for pair in event.items %}
{{ pair.0 }} = {{ pair.1 }}<br />
{% endfor %}
{% endfor %}
Without having my own method call... should I use something other than '.items'?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 db.Model 的“dynamic_properties”方法来检索 Expando 的属性,格式与“properties”方法相同(如 在 Model 类下)
请记住,这些函数不返回属性的值,但...“properties”返回属性名称的字典映射到其实现类(在本例中为 db.ReferenceProperty 和 db.DateTimeProperty),而“dynamic_properties”仅返回属性名称列表,因为 Expandos 无法将动态值映射到实现类。
为了获取属性的值,您必须使用
getattr(model, prop_name)
。没有办法纯粹在 Django 模板内运行此函数(没有 自定义标签库),但您可以像这样保留并重写您的方法......并重写您的模板以通过新的字典输入访问值:
You can use a db.Model's 'dynamic_properties' method to retrieve an Expando's properties, in the same format as the 'properties' method (as documented under the Model class)
Remember that those functions don't return a property's value, though... 'properties' returns a dictionary of property names mapped to their implementation class (db.ReferenceProperty and db.DateTimeProperty, in this case), and 'dynamic_properties' simply returns a list of property names, since Expandos can't map a dynamic value to an implementation class.
In order to get the property's value, you have to use
getattr(model, prop_name)
. There is no way to run this function purely inside a Django template (without a custom tag library), but you could keep and re-write your method like so...... and re-write your template to access the values via the new dictionary input: