[英]One-to-many relationships in datastore
There is a nice explanation of 1-to-many relationships in datastore here by Rafe Kaplan. Rafe Kaplan在这里对数据存储区中的一对多关系进行了很好的解释。 I tried to adapt that to a simpler case of
User
and Venue
. 我试图使它适应
User
和Venue
一个简单案例。 So user can go to many restaurants; 这样用户可以去很多餐馆; and I want to print the user email and the restaurants the user went to:
我想打印用户电子邮件和用户去的餐馆:
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)
This prints "club1 club2"
打印
"club1 club2"
But I want to associate "scott@example.com"
with the places he went to; 但是我想将
"scott@example.com"
与他去过的地方联系起来; so I want to print something like: "scott@example.com: club1, club2"
所以我想打印以下内容:
"scott@example.com: club1, club2"
Trying 试
for v in scott.venues:
self.response.out.write(userEmail)
self.response.out.write(v.venue)
gives the error: 给出错误:
self.response.out.write(userEmail)
NameError: global name 'userEmail' is not defined
What is the correct way of doing this? 正确的做法是什么? Thanks!
谢谢!
EDIT2 (re: answer by vonPetrushev) EDIT2 (回复:vonPetrushev的回答)
This seems to work: 这似乎可行:
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)
Displays: 显示:
scott@example.com went to:club1club22
EDIT (re: answer by vonPetrushev) 编辑 (回复:vonPetrushev的回答)
I am a little bit confused. 我有点困惑。
So I want to write a query like this 所以我想写一个这样的查询
query = User.all()
query.filter("userEmail =", "scott@example.com")
and display all the venues associated with this user. 并显示与此用户关联的所有场所。
It is not clear how User
and Venue
is connected. 目前尚不清楚
User
和Venue
的连接方式。
userEmail
is not a defined name in the scope of the for
loop. userEmail
不是for
循环范围内的已定义名称。 What you need is: 您需要的是:
for v in scott.venues:
self.response.out.write(scott.userEmail)
self.response.out.write(v.venue)
EDIT : Concerning your edit - if your goal is to make a joined query - you can't, not with the google app datastore. 编辑 :关于您的编辑-如果您的目标是进行联合查询-您不能,而不是使用Google App数据存储。 However, you can grab the user like this:
但是,您可以像这样抓住用户:
query = User.all()
query.filter("userEmail =", "scott@example.com")
results=query.fetch(1)
scott=results[0]
and then get the venues like scott.venues
. 然后获得
scott.venues
之类的场所。 The relation is defined in the line with db.ReferenceProperty
, which defines what is someuser.venues
and what is somevenue.user
. 该关系在
db.ReferenceProperty
行中定义,该行定义了someuser.venues
和somevenue.user
是什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.