gpt4 book ai didi

python - 使用 Google App Engine 从 db.ReferenceProperty 切换到 ndb?

转载 作者:太空宇宙 更新时间:2023-11-03 13:41:48 24 4
gpt4 key购买 nike

今天我在这里阅读了这篇关于如何建立我在 GAE REST API 中使用的一对多关系的文章。

https://cloud.google.com/appengine/articles/modeling

我认为这很简单,但后来我意识到我使用的是 ndb 而不是 db,所以我不能使用 db.ReferenceProperty。

这里我有一个模型路线

class Route(ndb.Model):

driver_id = ndb.IntegerProperty()
requester_id = ndb.IntegerProperty()
startpoint = ndb.GeoPtProperty(required=True)
endpoint = ndb.GeoPtProperty(required=True)
regular = ndb.BooleanProperty(required=True)
date_and_time = ndb.DateTimeProperty(required=True)
places_available = ndb.IntegerProperty()
val_lift = ndb.IntegerProperty()

这里我有我的模型 RegularDays,如果接收到的 JSON 中的 Regular 为 True,它将被使用

class RegularDays(ndb.Model):

route = db.ReferenceProperty(Route,
collection_name='regular_days')
Monday = ndb.BooleanProperty(required=True)
Tuesday = ndb.BooleanProperty(required=True)
Wednesday = ndb.BooleanProperty(required=True)
Thursday = ndb.BooleanProperty(required=True)
Friday = ndb.BooleanProperty(required=True)
Saturday = ndb.BooleanProperty(required=True)
Sunday = ndb.BooleanProperty(required=True)

所以我要做的就是这个。

if newroute.regular:
RegularDays(route=newroute,
Monday=route_json['Days']['Monday'],
Tuesday=route_json['Days']['Tuesday'],
Wednesday=['Days']['Wednesday'],
Thursday=route_json['Days']['Thursday'],
Friday=route_json['Days']['Friday'],
Saturday=route_json['Days']['Saturday'],
Sunday=route_json['Days']['Sunday']).put()

但现在我对如何更改此代码以使其与 NDB 一起工作感到非常困惑。

谢谢你的帮助

最佳答案

ndb 中的等效项是 KeyProperty :

Datastore key

Optional keyword argument: kind=kind, to require that keys assigned to this property always have the indicated kind. May be a string or a Model subclass.

您会发现在您的示例中只需替换属性名称就足够了,除了关键字 collection_name 将不再起作用:那是因为旧的 ReferenceProperty 做了一些在幕后为你工作,在引用的类中创建一个查询属性,试图让你的生活更轻松,但它被丢弃在 ndb 中,选择了一种更明确的方法,只存储键并让你担心实现细节。

如果您想知道,进行此更改的原因是自动属性非常易于使用,以至于通常会忽略真正发生的事情(眼不见,心不烦),并以很多额外的工作和查询需要花费大量时间进行优化。

这对你来说意味着不要写这行:

for phone in scott.phone_numbers:

您必须自己编写 phone_numbers 查询代码 :)

关于python - 使用 Google App Engine 从 db.ReferenceProperty 切换到 ndb?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29324279/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com