Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ndb query a model based upon KeyProperty instance

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?

like image 422
user993563 Avatar asked Sep 08 '26 17:09

user993563


1 Answers

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))
like image 64
Nick Johnson Avatar answered Sep 11 '26 18:09

Nick Johnson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!