在NDB中存储关系值的有效方法

在NDB中存储关系值的有效方法,第1张

在NDB中存储关系值的有效方法

我会尝试规范化您的模型,而不是使用非规范化模型:

class CourseInscription(ndb.Model):    member = ndb.KeyProperty(kind='User', required=True)    course = ndb.KeyProperty(kind='Course', required=True)    is_active = ndb.BooleanProperty(default=True)

然后,您可以添加类似

class Course(ndb.Model):    # all the stuff already there    @property    def members(self):        return CourseInscription.query(CourseInscription.course == self.key)

通常,我更喜欢只返回查询,让调用者决定直接调用它,或者添加更多过滤/排序,而不是直接执行 ndb.get_multi

我通常做的另一种不错的做法是使用它们的父级为关系实体构造id,因此我可以使用get by id轻松检查是否存在,而不必查询

class CourseInscription(ndb.Model):    # all the other stuff    @staticmethod    def build_id(user_key, course_key):        return '%s/%s' % (user_key.urlsafe(), course_key.urlsafe())# somewhere I can create an inscription likeCourseInscription(    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


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5663426.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存