App Engine 中的 db.ReferenceProperty() 与 ndb.KeyProperty [英] db.ReferenceProperty() vs ndb.KeyProperty in App Engine

查看:22
本文介绍了App Engine 中的 db.ReferenceProperty() 与 ndb.KeyProperty的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ReferenceProperty 在处理两个模块之间的引用方面非常有帮助.狐狸示例:

ReferenceProperty was very helpful in handling references between two modules. Fox example:

class UserProf(db.Model):
    name = db.StringProperty(required=True)

class Team(db.Model):
    manager_name = db.ReferenceProperty(UserProf, collection_name='teams')
    name = db.StringProperty(required=True)

  • 要通过团队实例获取manager_name",我们使用 team_ins.manager_name.
  • 为了获得由特定用户实例管理的团队",我们使用 user_instance.teams 并迭代.
  • 是不是看起来简单易懂?

    Doesn't it look easy and understandable?

    在使用 NDB 做同样的事情时,我们必须修改

    In doing same thing using NDB, we have to modify

    db.ReferenceProperty(UserProf, collection_name='teams') --> ndb.KeyProperty(kind=UserProf)

    • team_ins.manager_name.get() 会给你经理名字
    • 要让所有由特定用户管理的团队,我们必须做

    • team_ins.manager_name.get() would give you manager name
    • To get all team which are manger by particular user, we have to do

    for team in Team.query(Team.manager_name == user_ins.key): 
        print "team  name:", team.name
    

    正如你所看到的,在 db 中处理这些场景看起来比在 ndb 中更容易和可读.

    As you can see handling these kind of scenarios looks easier and readable in db than ndb.

    • 删除 ndb 中的 ReferenceProperty 的原因是什么?
    • 即使是 db 的查询 user_instance.teams 也会做与在 ndb 的 for 循环中所做的相同的事情.但是在 ndb 中,我们明确提到使用 for 循环.
    • 当我们执行 user_instance.teams 时,幕后发生了什么?

    提前致谢..

    推荐答案

    Tim 解释得很好.我们发现一个常见的反模式是使用引用属性并一次加载一个,因为符号entity.property1.property2"没有明确表示第一个点会导致数据库get"操作.因此,我们通过强制您编写entity.property1.get().property2"使其更加明显,并且通过简单地说entity.property1.get_async()" 用于一堆实体——这将单个批处理 get 操作排队而不会阻塞结果,并且当您下次使用entity.property1.get().property2"引用这些属性中的任何一个时,这不会启动另一个get 操作,但只是等待该批 get 完成(第二次执行此操作时,批 get 已经 完成).同样,进程内和内存缓存的集成也是免费的.

    Tim explained it well. We found that a common anti-pattern was using reference properties and loading them one at a time, because the notation "entity.property1.property2" doesn't make it clear that the first dot causes a database "get" operation. So we made it more obvious by forcing you to write "entity.property1.get().property2", and we made it easier to do batch prefetching (without the complex solution from Nick's blog) by simply saying "entity.property1.get_async()" for a bunch of entities -- this queues a single batch get operation without blocking for the result, and when you next reference any of these properties using "entity.property1.get().property2" this won't start another get operation but just waits for that batch get to complete (and the second time you do this, the batch get is already complete). Also this way in-process and memcache integration comes for free.

    这篇关于App Engine 中的 db.ReferenceProperty() 与 ndb.KeyProperty的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆