【发布时间】:2012-05-24 05:03:13
【问题描述】:
我正在 GAE 和 Python 2.7 运行时编写我的第一个 RESTful Web 服务;我已经开始使用 Guido 闪亮的新 ndb API。
但是,如果没有原始 db API 的隐式反向引用功能,我不确定如何解决特定情况。如果用户代理请求特定资源并且这些资源被移除 1 度:
host/api/kind/id?depth=2
鉴于相关实体的种类在开发时是未知的,从一对多关系中的“一”中发现相关实体集合的最佳方法是什么?
由于后一个限制,我无法使用previous SO inquiry 中描述的替换查询。我的模型在运行时可定义(因此不是硬编码)这一事实阻止我使用查询来过滤匹配键的属性。
由于数据存储限制阻止我过滤没有指定种类的属性,祖先和其他无种类查询也被排除在外。
到目前为止,我唯一的想法(除了恢复到 db api)是使用跨组事务在“one”上写入我自己的引用,或者通过更新 ndb.StringProperty(repeat= True) 在引入新类型的实体时包含所有相关类型,或者每次将相关的“许多”实体写入数据存储时,只需在“一个”ndb.KeyProperty(repeat=True) 上维护一个键列表.
我希望比我更有经验的人能提出更好的方法。
鉴于 jmort253 的建议,我将尝试通过改编自文档的具体示例来扩充我的问题:
class Contact(ndb.Expando):
""" The One """
# basic info
name = ndb.StringProperty()
birth_day = ndb.DateProperty()
# If I were using db, a collection called 'phone_numbers' would be implicitly
# created here. I could use this property to retrieve related phone numbers
# when this entity was queried. Since NDB lacks this feature, the service
# will neither have a reference to query nor the means to know the
# relationship exists in the first place since it cannot be hard-coded. The
# data model is extensible and user-defined at runtime; most relationships
# will be described only in the data, and must be discoverable by the server.
# In this case, when Contact is queried, I need a way to retrieve the
# collection of phone numbers.
# Company info.
company_title = ndb.StringProperty()
company_name = ndb.StringProperty()
company_description = ndb.StringProperty()
company_address = ndb.PostalAddressProperty()
class PhoneNumber(ndb.Expando):
""" The Many """
# no collection_name='phone_numbers' equivalent exists for the key property
contact = ndb.KeyProperty(kind='Contact')
number = ndb.PhoneNumberProperty()
【问题讨论】:
-
嗨,你能不能举个例子来帮助你更好地理解这个问题。许多人都是视觉的,所以看到可能有助于澄清你的问题。祝你好运! :)
-
如果您不知道要查找的实体类型,那么在获取它们时您将如何处理它/它们?
-
服务层将简单地将它发现的相关实体序列化为明确请求实体的 JSON 表示。由客户端应用程序决定如何使用它们;服务器不在乎。
标签: python google-app-engine google-cloud-datastore app-engine-ndb