Python 获取模板中的相关对象
在应用程序引擎中,我有这样一个模型:Python 获取模板中的相关对象,python,google-app-engine,app-engine-ndb,Python,Google App Engine,App Engine Ndb,在应用程序引擎中,我有这样一个模型: class Matchday(ndb.Model): num = ndb.IntegerProperty() name = ndb.StringProperty() class Match(ndb.Model): matchday = ndb.KeyProperty(kind='Matchday') home = ndb.KeyProperty(kind='Team') away = ndb.KeyProperty(
class Matchday(ndb.Model):
num = ndb.IntegerProperty()
name = ndb.StringProperty()
class Match(ndb.Model):
matchday = ndb.KeyProperty(kind='Matchday')
home = ndb.KeyProperty(kind='Team')
away = ndb.KeyProperty(kind='Team')
date = ndb.DateTimeProperty()
matchdays = Matchday.query().order(Matchday.num).fetch()
matches = Match.query().order(Match.date).fetch()
我检索Matchdays的所有项目,并进行如下匹配:
class Matchday(ndb.Model):
num = ndb.IntegerProperty()
name = ndb.StringProperty()
class Match(ndb.Model):
matchday = ndb.KeyProperty(kind='Matchday')
home = ndb.KeyProperty(kind='Team')
away = ndb.KeyProperty(kind='Team')
date = ndb.DateTimeProperty()
matchdays = Matchday.query().order(Matchday.num).fetch()
matches = Match.query().order(Match.date).fetch()
并将它们传递给模板(使用jinja2)。
在模板上,我想列出所有的匹配日,并用嵌套列表列出这些匹配日内的对应匹配项,如下所示
% for matchday in matchdays %}
{% for match in matchday.matches %}
{{ <<do somethin with the match here>> }}
{% endfor %}
{% endfor %}
%用于matchdays%中的matchday%
{matchday.matches%}
{{ }}
{%endfor%}
{%endfor%}
这显然行不通。在嵌套for循环中,如何仅检索属于特定匹配日的匹配?这可以通过我实现的KeyProperty实现吗,或者我必须更改我的模型吗?KeyProperty可以与其他同类键进行比较
matches = Match.query(Match.matchday == matchday.key).fetch()
编辑:
将此添加到Matchday模型中,您的代码就会正常工作
@property
matches = Match.query(Match.matchday == self.key).fetch()
每次模板调用
{%for match in matchday.matches%}
时,这将执行一个查询:
class Matchday(ndb.Model):
num = ndb.IntegerProperty()
name = ndb.StringProperty()
def matches(self):
return Match.query(Match.matchday == self.key).order(Match.date)
看看我的应用程序,谢谢。唯一的问题是,这在模板中不起作用。我考虑在Matchdays模型上使用repeated=True的KeyProperty,将一对多关系表示为键列表