One-to-Many Example in NDB

I am trying to create an ndb.Model class, e.g. students and topics

class Subject(ndb.Model): name = ndb.StringProperty() class Student(ndb.Model): name = ndb.StringProperty() subject = ndb.KeyProperty(kind=Subject) 

One student can have many items. How to add and save them in this model. I could not find a single example of this. For the String .. property, there is a field property ie repeat = true

How to achieve this and is there any working example on the Internet. Sorry if this is a recurring question, but I tried with my limited skills to search this forum.

+7
source share
4 answers

When I need 1 for many, I use duplicate keyProperties. The code:

 class Subject(ndb.Model): name = ndb.StringProperty() class Student(ndb.Model): name = ndb.StringProperty() subjects = ndb.KeyProperty(kind='Subject', repeated=True) 

template:

 {% for subject in student.subjects %} {{subject.get().name}} {% endfor %} 

ndb is nosql, so you will not find a reference to the parent in the child. However, you can add it like this. Do not forget to specify the key value for the student when creating a new object.

 class Subject(ndb.Model): name = ndb.StringProperty() student = ndb.KeyProperty(kind='Student') class Student(ndb.Model): name = ndb.StringProperty() subjects = ndb.KeyProperty(kind='Subject', repeated=True) 
+7
source

Use the theme as the key.

 me = Student(key_name='KurzedMetal') programming = Subject(key_name='Programming') programming.put() me.subject = programming.key() me.put() 
+1
source

Definition:

 class Subject(ndb.Model): name = ndb.StringProperty() class Student(ndb.Model): name = ndb.StringProperty() subject = ndb.KeyProperty(kind=Subject,repeated=True) 

Using:

 subject1 = Subject() subject1.put() subject2 = Subject() subject2.put() student = Student() student.subject.append(subject1.key) student.subject.append(subject2.key) student.put() 
+1
source

This seems like an old question. If someone else needs it now, you should look at Structured Properties https://developers.google.com/appengine/docs/python/ndb/properties#structured . The example is very simple and straightforward.

0
source

All Articles