将一个实体的 ID 重新用于不同类型的其他实体 - 理智的想法? [英] re-using an entity's ID for other entities of different kinds - sane idea?

查看:14
本文介绍了将一个实体的 ID 重新用于不同类型的其他实体 - 理智的想法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 (python) 应用程序正在使用多个实体,其中许多实体是 1:1 的关系.例如:

My (python) app is using several entities, many of them in a 1:1 relationship. For example:

class Main(ndb.Model):
    field1 = ndb.StringProperty()
    #peer_key = ndb.KeyProperty(kind='Peer')

class Peer(ndb.model):
    field2 = ndb.IntegerProperty()
    #main_key = ndb.KeyProperty(kind='Main')

一些 Main 实体可能有一个 Peer 实体(在 Main 实体之后创建)完全是 1:1 的关系.

Some of the Main entities may have a Peer entity (created after the Main entity) in exactly a 1:1 relationship.

我在想,在创建 Peer 实体时,我可以简单地指定一个数字 ID 等于相应的 Main 实体的 ID(由数据存储自动生成,因此保证是唯一的):

I was thinking that at creation of the Peer entity I could simply specify a numerical ID equal to the corresponding Main entity's ID (auto-generated by the datastore and thus guaranteed to be unique):

main_entity = Main(field1='blah')
main_entity.put()

peer_entity = Peer(id=main_entity.key.id(), field2=10)
peer_entity.put()

通过这种方式,我可以显着简化我的应用程序的逻辑,而无需存储和处理实体键来交叉引用这些实体,尤其是在跨请求传递它们时.例如,在我拥有主要实体的上下文中,我可以简单地执行以下操作:

This way I could significantly simplify my app's logic, without the need of storing and processing the entity keys to cross-reference these entities, especially when passing them across requests. For example, in a context where I have the main entity I could simply do:

peer_entity = Peer.get_by_id(main_entity.key.id())

同样,在我拥有对等实体的上下文中:

Similarly, in a context where I have the peer entity:

main_entity = Main.get_by_id(peer_entity.key.id())

根据文档,键只是(kind, id) 对,意思是只要种类不同,id 唯一,我不应该有问题.到目前为止(在开发服务器上)我所做的测试似乎工作正常.

According to the documentation keys are just (kind, id) pairs, meaning as long as the kinds are different and the ids are unique I shouldn't have problems. The tests I've done so far (on the development server) appear to be working fine.

我的想法是正确的还是我遗漏了什么(到目前为止我的测试很幸运)?

Is my thinking correct or am I missing something (and was just lucky so far in my testing)?

推荐答案

我多年来一直使用这种方法,从未遇到任何问题.

I use this approach all the time for many years, and never had any problems.

例如,每次更新实体时,每个索引字段也会更新.出于这个原因,我经常将一个复杂的实体拆分为很少更新"的部分和经常更新的"部分,并为两个实体使用不同种类但相同的 ID,例如AdEntity 和 AdCounterEntity.这样,正如您正确观察到的,应用逻辑得到了简化,因为您只需要记住一个 ID 即可根据需要检索两个实体.

For example, every time you update an entity, every indexed field is updated too. For this reason, I often split a complex entity into "rarely updated" part and "frequently updated" part, and use different kinds but the same ID for both entities, e.g. AdEntity and AdCounterEntity. This way, as you correctly observed, the app logic is simplified as you need to remember only one ID to retrieve both entities as necessary.

这篇关于将一个实体的 ID 重新用于不同类型的其他实体 - 理智的想法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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