re-using an entity's ID for other entities of different kinds - sane idea?

谁都会走 提交于 2019-11-26 06:48:57

问题


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\')

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

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())

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)?


回答1:


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

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.



来源:https://stackoverflow.com/questions/34954102/re-using-an-entitys-id-for-other-entities-of-different-kinds-sane-idea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!