3
votes

I have a simple ndb model as follows:

class TaskList(ndb.Model):
    title = ndb.StringProperty()
    description = ndb.TextProperty()
    priority = ndb.IntegerProperty()


class UserProfile(ndb.Model):
    user = ndb.UserProperty()
    tasks = ndb.KeyProperty(TaskList)

As known, a TaskList object will have an Entity Kind Entity Key and an ID. Given an ID say 7. I can very well get the object with ID 7 as follows:

task = ndb.Key(TaskList, 7).get()

But how do i get a user who has the task ID 7?

I tried:

tsk = ndb.Key(TaskList, 7).get() 
user = UserProfile.query(UserProfile.tasks  == tsk.key)

It works, but is there a better method?

1
Is there a reason you are not able to have a user property on the TaskList entity itself? - Sologoub

1 Answers

5
votes

You're nearly there - but there's no need to fetch the task, just to use its key property again:

task_key = ndb.Key(TaskList, 7)
user = UserProfile.query(UserProfile.tasks == task_key)

or equivalently:

user = UserProfile.query(UserProfile.tasks == ndb.Key(TaskList, 7))