Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One-To-Many Example in NDB

I am trying to create ndb.Model class like Students and subjects

class Subject(ndb.Model):
     name = ndb.StringProperty()

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

One Student can have many Subjects. How to add and store these in this Model. I could not find any example of it. For String Property .. there is field property i.e. repeat=true

How to achieve this and is there any working example on the web. Sorry if it is duplicate question but I tried with my limited skills to search this forum.

like image 547
Anjana Avatar asked Apr 09 '12 17:04

Anjana


3 Answers

When I need 1 to many I use repeated keyProperties. 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 reference to the parent in the child. However, you could add it like that. Don't forget to set student key value when creating a new subject.

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)
like image 94
Cyril Avatar answered Oct 27 '22 15:10

Cyril


Use the subject as a key.

me = Student(key_name='KurzedMetal')
programming = Subject(key_name='Programming')
programming.put()
me.subject = programming.key()
me.put()
like image 33
KurzedMetal Avatar answered Oct 27 '22 15:10

KurzedMetal


Definition:

class Subject(ndb.Model):
     name = ndb.StringProperty()

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

Usage:

subject1 = Subject()
subject1.put()
subject2 = Subject()
subject2.put()
student = Student()
student.subject.append(subject1.key)
student.subject.append(subject2.key)
student.put()
like image 1
Wade Avatar answered Oct 27 '22 15:10

Wade