ndb 建模一对多:重复 KeyProperty 与外键的优点 [英] ndb modelling one-to-many: merits of repeated KeyProperty vs foreign key
问题描述
我的问题是关于在 ndb 中建模一对多关系.我知道这可以通过(至少)两种不同的方式完成:使用重复的属性或使用外键".我在下面创建了一个小例子.基本上我们有一个可以有任意数量标签的文章.让我们假设一个标签可以被删除,但在添加后不能更改.我们还假设我们不担心交易安全.
My question is about modelling one-to-many relations in ndb. I understand that this can be done in (at least) two different ways: with a repeated property or with a 'foreign key'. I have created a small example below. Basically we have an Article which can have an arbitrary number of Tags. Let's assume that a Tag can be removed but cannot be changed after it has been added. Let's also assume that we don't worry about transactional safety.
我的问题是:建模这些关系的首选方法是什么?
我的考虑:
- 方法 (A) 需要为每个添加到一个标签的标签写入两次文章(一个用于文章,一个用于标签)而方法(B) 只需要一次写入(仅标签).
- 方法 (A) 利用获取文章的所有标签时 ndb 的缓存机制,而在方法 (B) 的情况下,需要一个查询(另外还有一些自定义缓存)
这里有我遗漏的地方吗?还有其他需要考虑的因素吗?
Are there some things that I'm missing here, any other considerations that should be taken into account?
非常感谢您的帮助.
示例(A):
class Article(ndb.Model):
title = ndb.StringProperty()
# some more properties
tags = ndb.KeyProperty(kind="Tag", repeated=True)
def create_tag(self):
# requires two writes
tag = Tag(name="my_tag")
tag.put()
self.tags.append(tag)
self.put()
def get_tags(self):
return ndb.get_multi(self.tags)
class Tag(ndb.Model):
name = ndb.StringProperty()
user = ndb.KeyProperty(Kind="User") # User that created the tag
# some more properties
示例(B):
class Article(ndb.Model):
title = ndb.StringProperty()
# some more properties
def create_tag(self):
# requires one write
tag = Tag(name="my_tag", article=self.key)
tag.put()
def get_tags(self):
# obviously we could cache this query in memcache
return Tag.gql("WHERE article :1", self.key)
class Tag(ndb.Model):
name = ndb.StringProperty()
article = ndb.KeyProperty(kind="Article")
user = ndb.KeyProperty(Kind="User") # User that created the tag
# some more properties
推荐答案
您是否看过以下有关使用 结构化属性
https://developers.google.com/appengine/docs/python/ndb/properties#structured.那里关于 Contact
和 Addresse
的简短讨论可能会简化您的问题.另请参阅 https://developers.google.com/appengine/docs/python/ndb/queries#filtering_structured_properties.讨论很短.
Have you looked at the following about using Structured Properties
https://developers.google.com/appengine/docs/python/ndb/properties#structured . The short discussion there about Contact
and Addresse
may simplify your problem. Also look at https://developers.google.com/appengine/docs/python/ndb/queries#filtering_structured_properties. The discussions are very short.
另外,展望不允许连接的事实,选项 A
看起来更好.
Also, looking ahead to the fact that joins are not allowed, option A
looks better.
这篇关于ndb 建模一对多:重复 KeyProperty 与外键的优点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!