【问题标题】:How to access properties of referenced objects in Jinja2 templates (Google App Engine)如何访问 Jinja2 模板中引用对象的属性(Google App Engine)
【发布时间】:2014-10-29 19:10:10
【问题描述】:

考虑 Google App Engine 中的以下数据模型

class A(ndb.Model):
    name = ndb.StringProperty()
    b = ndb.KeyProperty(Kind='B')

class B(ndb.Model):
    name = StringProperty()

现在假设我在 Python Http 请求处理程序中执行了这个查询

entities = A.query().fetch(200)

我将实体作为模板值传递给 Jinja2 模板

我在其中迭代 A 对象,例如

{%for a in entities%}

  {{a.name}}

{% endfor %}

问题是:如何在 Jinja2 模板中访问 A 引用的 B 对象的属性?像 {{a.b.name}}

【问题讨论】:

  • a.b.get().name 可能工作...

标签: python google-app-engine jinja2 google-cloud-datastore app-engine-ndb


【解决方案1】:

你有实体的密钥(b),所以你可以直接得到它:

{% set b_entity = a.b.get() %}
{{ b_entity.name }}

(如果实体中有其他属性,请使用set。这样您只需执行一次get()

【讨论】:

【解决方案2】:

这是ndb asyc api 可能有用的情况...

@ndb.tasklet
def get_b_instances_from_a_instances(a_instance):
    b_instance = yield a_instance.b.get_async()
    raise ndb.Return((a_instance, b_instance))

entities = A.query().map(get_b_instances_from_a_instances, limit=200)

现在你的 entities will be a list 的 2 元组每个都有一个 A 的实例,它是 B 的对应实例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-14
    • 1970-01-01
    • 1970-01-01
    • 2011-01-22
    • 2019-02-09
    • 2012-05-01
    • 2010-09-10
    • 2011-06-08
    相关资源
    最近更新 更多