栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/661468.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号