How to achive Join scenario in Google Datastore ndb(Python library)

1 view
Skip to first unread message

akshar via StackOverflow

unread,
May 10, 2017, 5:33:10 AM5/10/17
to gcd-stac...@googlegroups.com

I have two kinds:

class Professor(ndb.Model):
    name = ndb.StringProperty()
    email = ndb.StringProperty()

class Student(ndb.Model):
    professor = ndb.KeyProperty(kind=Professor)
    name = ndb.StringProperty()
    age = ndb.IntegerProperty()

I want to find all the Student entities where Professor name is "Snape". How can I do this?



Please DO NOT REPLY directly to this email but go to StackOverflow:
http://stackoverflow.com/questions/43888556/how-to-achive-join-scenario-in-google-datastore-ndbpython-library

akshar via StackOverflow

unread,
May 13, 2017, 10:38:09 AM5/13/17
to gcd-stac...@googlegroups.com

I have two kinds:

class Professor(ndb.Model):
    name = ndb.StringProperty()
    email = ndb.StringProperty()

class Student(ndb.Model):
    professor = ndb.KeyProperty(kind=Professor)
    name = ndb.StringProperty()
    age = ndb.IntegerProperty()

I want to find all the Student entities where Professor name is "Snape". How can I do this?

Or if I take the "One To Many" example of https://cloud.google.com/appengine/articles/modeling. Then I want to find all the PhoneNumber entities where Contact.name is "scott". How to do this.

The appengine example only tells how to filter on PhoneNumber attributes. What if I want to filter on the related Kind, i.e Contact attributes.

Askar via StackOverflow

unread,
May 13, 2017, 10:38:11 AM5/13/17
to gcd-stac...@googlegroups.com

You can do something like this.

# professor model
class Professor(ndb.Model):
    name = ndb.StringProperty()
    email = ndb.StringProperty()

# student model
class Student(ndb.Model):
    name = ndb.StringProperty()
    age = ndb.IntegerProperty()

snape = ndb.Key(Professor, 'snape')
Professor(name="Professor Snape", email="sn...@blah.edu", key=snape).put()


st1 = Student(name="Akshar", age=18, parent=snape)
st2 = Student(name="Greg", age=19, parent=snape)
st3 = Student(name="Alex", age=18, parent=snape)

st1.put()
st2.put()
st3.put()

# so lets say give me all students that has class with Professor Snape
for student in Student.query(ancestor=snape).fetch(10):
    print student.name

# You should get something:
Akshar
Greg
Alex


Please DO NOT REPLY directly to this email but go to StackOverflow:
http://stackoverflow.com/questions/43888556/how-to-achive-join-scenario-in-google-datastore-ndbpython-library/43954339#43954339
Reply all
Reply to author
Forward
0 new messages