Efficient Way To Store Relation Values In Ndb
Solution 1:
I'd try to normalize your model instead of going for a de-normalized one:
class CourseInscription(ndb.Model):
member= ndb.KeyProperty(kind='User', required=True)
course = ndb.KeyProperty(kind='Course', required=True)
is_active = ndb.BooleanProperty(default=True)
Then, you can just add something like
classCourse(ndb.Model):# all the stuff already there@propertydefmembers(self):
return CourseInscription.query(CourseInscription.course == self.key)
In general, I prefer to just return the query and let the caller decide to even call it directly or add some more filtering/sorting instead of doing ndb.get_multi directly.
Another nice touch I usually do is to construct the id for the relational entities using their parents, so I can easily check for existence with a get by id instead of having to query
classCourseInscription(ndb.Model):
# all the other stuff @staticmethoddefbuild_id(user_key, course_key):
return'%s/%s' % (user_key.urlsafe(), course_key.urlsafe())
# somewhere I can create an inscription like
CourseInscription(
id=CourseInscription.build_id(user_key, course_key),
user=user_key, course=course_key, is_active=True
).put()
# somewhere else I can check if a User is in a Course by just getting... no queries neededif ndb.Key(CourseInscription, CourseInscription.build_id(user, course)).get():
# Then the user is in the course!else:
# then it's not
Solution 2:
It makes perfect sense for the members and instructors to belong to the club in addition to being referenced by the courses. Thinking of the use-case, the member would need to join the club before they joined a course offered by the club (though this may happen at the same time of course). It is also significantly more efficient to have the members/instructors referenced directly (in the club) rather than having to traverse the courses each time. Your trade-off comes in additional code maintenance, but this seems justified in this case.
Regarding the active course filter, you may wish to consider an 'active' course list and an 'inactive' course list for the club: once a course is not longer offered, move it to the 'inactive' list (and remove it from the 'active' list).
Post a Comment for "Efficient Way To Store Relation Values In Ndb"