我有两种:
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()
我想找到教授名字是“Snape”的所有学生实体。我怎么能这样做?
或者如果我采用https://cloud.google.com/appengine/articles/modeling的“一对多”示例。然后我想找到Contact.name为“scott”的所有PhoneNumber实体。怎么做。
appengine示例仅说明如何过滤PhoneNumber属性。如果我想过滤相关的Kind,即Contact属性,该怎么办?
答案 0 :(得分:1)
为此,我建议使用ndb.KeyProperty
作为学生模型的属性来引用给定的教授。
class Professor(ndb.Model):
name = ndb.StringProperty()
class Student(ndb.Model):
name = ndb.StringProperty()
prof = ndb.KeyProperty()
使用上述实体种类,可以使用仅限密钥的查询查询名称为“Snape”的所有教授,然后查询所有教授为one of the retrieved keys的学生。
prof_keys = Professor.query().fetch(100, keys_only=True)
if len(prof_keys) < 1:
print "Cannot a given professor's students"
return
students = Student.query(Student.prof.IN(prof_keys)).fetch(100)
if len(students) < 1:
print "Found no students whose professor is Snape"
return
for student in students:
print "Found student named {} whose professor is Snape".format(student.name)
答案 1 :(得分:0)
你可以这样做。
# 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="snape@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