NDB查询:ndb.KeyProperty的反向关系

时间:2014-05-13 14:19:12

标签: python google-app-engine app-engine-ndb

我是这个模特

class User(ndb.Model):
    username = ndb.StringProperty()
    password = ndb.StringProperty()
    token = ndb.StringProperty(default="x")
    follows = ndb.KeyProperty(kind="User", repeated=True)
    picture = ndb.StringProperty()

现在我知道,对于每个用户,他关注的是什么人。 但是,我怎么知道跟随我的人呢? 例如:

A.follows=[B,..]
C.follows=[B,..]
B.getWhoFollowsMe = [A,C]

基本上,我如何创建getWhoFollowsMe函数?

2 个答案:

答案 0 :(得分:3)

您可以使用@ Hernan的功能,但为方便起见,您也可以将其作为属性或ClassMethod实现。

class User(ndb.Model):
    username = ndb.StringProperty()
    password = ndb.StringProperty()
    token = ndb.StringProperty(default="x")
    follows = ndb.KeyProperty(kind="User", repeated=True)
    picture = ndb.StringProperty()

    @property
    def followers(self):
        return User.query().filter(self.follows == self.key).fetch(1000)

因此稍后访问它

user.followers

但是,也许我的回答是过分的,我认为@Hernan应该是正确接受的

答案 1 :(得分:2)

def getWhoFollowsMe(me_key):
  return User.query().filter(User.follows==me_key)