【发布时间】:2023-03-16 16:15:01
【问题描述】:
Rafe Kaplan 对数据存储区here 中的一对多关系进行了很好的解释。我试图将其适应User 和Venue 的更简单情况。所以用户可以去很多餐馆;我想打印用户电子邮件和用户去过的餐馆:
class User(db.Model):
userEmail = db.StringProperty()
class Venue(db.Model):
user = db.ReferenceProperty(User,
collection_name="venues")
venue = db.StringProperty()
class OneToMany(webapp.RequestHandler):
def get(self):
scott = User(userEmail="scott@example.com")
scott.put()
Venue(user=scott,
venue="club1").put()
Venue(user=scott,
venue="club2").put()
for v in scott.venues:
self.response.out.write(v.venue)
这打印"club1 club2"
但我想将"scott@example.com"与他去过的地方联系起来;所以我想打印类似:"scott@example.com: club1, club2"
尝试
for v in scott.venues:
self.response.out.write(userEmail)
self.response.out.write(v.venue)
给出错误:
self.response.out.write(userEmail)
NameError: global name 'userEmail' is not defined
这样做的正确方法是什么?谢谢!
EDIT2(回复:vonPetrushev 的回答)
这似乎有效:
query = User.all()
query.filter("userEmail =", "scott@example.com")
results=query.fetch(1)
scott=results[0]
self.response.out.write("%s went to:" % scott.userEmail)
for venue in scott.venues:
self.response.out.write(venue.venue)
显示:
scott@example.com went to:club1club22
编辑(回复:vonPetrushev 的回答)
我有点困惑。
所以我想写一个这样的查询
query = User.all()
query.filter("userEmail =", "scott@example.com")
并显示与该用户关联的所有场所。
不清楚User和Venue是如何连接的。
【问题讨论】:
标签: python google-app-engine google-cloud-datastore one-to-many