python - 数据存储中的一对多关系

标签 python google-app-engine google-cloud-datastore one-to-many

在数据存储中有一对多关系的很好解释 here拉夫卡普兰。我试图将其适应更简单的 UserVenue 情况。所以用户可以去很多餐馆;我想打印用户电子邮件和用户去过的餐馆:

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 去了:club1club22

编辑(回复:vonPetrushev 的回答)

我有点困惑。

所以我想写这样一个查询

query = User.all()
query.filter("userEmail =", "scott@example.com")

并显示与该用户关联的所有场所。

目前尚不清楚UserVenue 是如何连接的。

最佳答案

userEmail 不是 for 循环范围内的定义名称。你需要的是:

for v in scott.venues:
    self.response.out.write(scott.userEmail)
    self.response.out.write(v.venue)

编辑:关于您的编辑 - 如果您的目标是进行联合查询 - 您不能,不能使用谷歌应用程序数据存储。但是,您可以像这样捕获用户:

query = User.all()
query.filter("userEmail =", "scott@example.com")
results=query.fetch(1)
scott=results[0]

然后获取像 scott.venues 这样的 field 。该关系在 db.ReferenceProperty 行中定义,它定义了什么是 someuser.venues 和什么是 somevenue.user

关于python - 数据存储中的一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4293191/

相关文章:

google-app-engine - Google App Engine - 哪些工具可以在本地编辑数据存储?

python - Google App Engine 数据库查询内存使用情况

regression - 理解 tf.keras 中线性回归模型调整的问题

python - 谁能明白为什么我的 python 正则表达式搜索只输出 "0"s?

python - 在 GAE 中保留任何/所有 Python 数据库对象的审计跟踪

python - 当 localhost 和 MacOSX 正常工作时,可以通过本地 ip 地址访问 AppEngine SDK 站点

google-app-engine - Appengine LogService 有一个未记录的配额 - 每天最多 1000000 次读取,知道解决方法吗?

python - 当我打开Pygame时,它总是崩溃

python - 如何使用python获取arduino端口

java - Google Cloud Datastore 过滤数据,其中包含列表中的项目