There are posts on how to set, get, KeyProperty/StructuredProperty, but nothing tells me how to use NDB for modeling many-to-one.
I have two Models:
class Department(ndb.Model):
department_id = ndb.IntegerProperty()
name = ndb.StringProperty()
class Student(ndb.Model):
student_id = ndb.IntegerProperty()
name = ndb.StringProperty()
dept = ndb.KeyProperty(Kind=Department)
How is the many-to-one is ensured, i.e whenever there is an insert into student record, it has to validate department key w.r.t to department datastore?
How do you insert student record to ensure many-to-one relationship?
Option 1:
# Insert student record without checking for valid dept id. GAE automatically validates
student = Student(student_id=...., dept=ndb.Key(Department, input_dept_id))
Option 2:
# check for valid dept id and then insert student record
dept_key = ndb.Key(Department, input_dept_id)
if(dept_key.get()):
student = Student(student_id=...., dept=dept_key)
I tried option 1 with an dept_id not in department entities and it was able to insert that student entity. I'm fairly new to GAE.
Student(student_id=...., dept=ndb.Key("Department", input_dept_id))
– Tim Hoffman