ndb.KeyProperty 的集合名称

问题描述 投票:0回答:1

db.ReferenceProperty
允许使用
collection_name
参数,指定引用对象 R 如何查询包含 R 作为引用的对象。

我没有看到类似的论点

ndb.KeyProperty
。人们如何解决这个问题?

google-app-engine
1个回答
2
投票

当我切换到

ndb
时需要一点时间来适应,但实际上更简单。
collection_name
只是查询的语法糖,你可以自己进行查询:

MyEntity(ndb.Model):
    a_key = ndb.KeyProperty()

entities = MyEntity.query(MyEntity.a_key == some_key)

下面你可以看到来自这个 Google 群组的一个更完整的示例,它在引用的类(“one”;本例中为 Post)上创建一个新的

@property
,而不是在引用类(“many”;;本例中的评论):

db:

class Post(db.Model):
    content = db.TextProperty(required = True)   
   
class Comment(db.Model):
    """ Comment object with many-to-one relationship """
    content = db.TextProperty(required = True) 
    post = db.ReferenceProperty(Post, collection_name='comment_set')

ndb:

class Post(ndb.Model):
    content = ndb.TextProperty(required = True)   

    @property
    def comment_set(self):
        return Comment.query(Comment.post == self.key)

class Comment(ndb.Model):
    """ Comment object with many-to-one relationship """
    content = ndb.TextProperty(required = True) 
    post = ndb.KeyProperty(kind=Post)
© www.soinside.com 2019 - 2024. All rights reserved.