在app引擎中,我有一个这样的模型:
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 %}
这显然不起作用。在嵌套的for循环中,我如何只检索属于特定比赛日的匹配?可以用我实现的KeyProperty来完成,还是我必须改变我的模型?
答案 0 :(得分:1)
KeyProperty可与其他同类型的键相媲美
matches = Match.query(Match.matchday == matchday.key).fetch()
编辑:
将此添加到Matchday模型,您的代码可以正常工作
@property
matches = Match.query(Match.matchday == self.key).fetch()
答案 1 :(得分:0)
每次模板调用{% 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)