0
votes

I have User model and another model is user token

 class User(EndpointsModel):
    name = ndb.StringProperty()

    @classmethod
    def get_by_name(cls,name)
         return cls.query(cls.name == name).get()

2 model is user token

 class Token(EndpointsModel):
    user = ndb.KeyProperty()
    token = ndb.StringProperty()

    @classmethod
    def get_by_user(cls, key):
        return   cls.query(cls.token == key).get()

Now i fetch data from user

  data = User.get_by_name('jaskaran')

when i try to fetch token then it return me None

 print( Token.get_by_user(data.key) )

this is return None How can i fetch data from token with the help of user keyProrperty?

1

1 Answers

1
votes

I think that you may be looking for ancestor queries, that according to the official documentation, look like this:

As the example in the docs shows:

purchases = Purchase.query(
    Purchase.customer == customer_entity.key).fetch()

This applied to your use case will be then something like:

class Token(EndpointsModel):
    user = ndb.KeyProperty(kind=User) #added kind User in key property, just in case
    token = ndb.StringProperty()

    @classmethod
    def get_by_user(cls, key):
        return   cls.query(cls.token == key).fetch()

###Fetching data 
data = User.get_by_name('jaskaran')

##HERE WILL BE GOOD TO PRINT DATA.KEY, FOR EXAMPLE,
##TO MAKE SURE THAT YOU ARE ACTUALLY RETRIEVING SOMETHING
print(data.key)

print(Token.get_by_user(data.key)

As a side note, the docs also explain that Account.get_by_id(...) is faster than Account.query(...).get(), therefore removing the .get() will be a good update to the code.