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

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x