EsseTi
EsseTi

Reputation: 4301

NDB Query: reverse relationships of ndb.KeyProperty

i've this model

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()

right now i know, for each user, what are the people he follows. But, how can i know the people that follows me? example:

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

basically, how can i create the getWhoFollowsMe function?

Upvotes: 0

Views: 234

Answers (2)

Hernán Acosta
Hernán Acosta

Reputation: 695

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

Upvotes: 2

Jimmy Kane
Jimmy Kane

Reputation: 16865

You can use @Hernan's function, but you can also implement it as a property or ClassMethod for convenience.

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)

Thus later access it like

user.followers

But yeah maybe my answer is excessive and I think @Hernan's should be the correct accepted one

Upvotes: 3

Related Questions