GAE Python: How to use NDB KeyProperty models for many-to-one relationship?
<p>There are posts on how to <a href="http://stackoverflow.com/questions/14192331/how-to-set-an-ndb-keyproperty">set</a>, <a href="http://stackoverflow.com/questions/19868410/how-do-i-use-ndb-keyproperty-properly-in-this-situation">get</a>, <a href="http://stackoverflow.com/questions/14072491/app-engine-structured-property-vs-reference-property-for-one-to-many-relationsh">KeyProperty/StructuredProperty</a>, but nothing tells me how to use NDB for modeling many-to-one.</p>

<p>I have two Models:</p>

<pre><code>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)
</code></pre>

<p>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? </p>

<p>How do you insert student record to ensure many-to-one relationship?</p>

<p>Option 1:</p>

<pre><code># Insert student record without checking for valid dept id. GAE automatically validates
student = Student(student_id=...., dept=ndb.Key(Department, input_dept_id))
</code></pre>

<p>Option 2:</p>

<pre><code># 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)
</code></pre>

<p>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.</p>

<p>According to the documentation (<a href="https://cloud.google.com/appengine/docs/python/datastore/entities" rel="nofollow">https://cloud.google.com/appengine/docs/python/datastore/entities</a>), "The Datastore API does not distinguish between creating a new entity and updating an existing one". That is, the put() method will either create a non-existing entity or update an existing one.</p>

<p>So, Option 2 seems the way to go. (Option 1 indeed does not provide any validation)</p>

python google-app-engine