seven-down
seven-down

Reputation: 126

Use Datastore Entity's ID or Key in ProtoRPC.Message

When transmitting references to other Datastore entities using the Message class from ProtoRPC, should I use str(key) or key.id(). The first one is a String the second one is a long.

Does it make any difference in the end? Are there any restrictions?

It appears that when filtering queries, the same results come out.

Thanks

Upvotes: 1

Views: 390

Answers (1)

bossylobster
bossylobster

Reputation: 10163

It depends on what your goal is and whether or not you're using db or nbd.

If you use str(key) you'll get an entity key and will need to construct a new key (on the server depending on that value). Using ndb, I would recommend using key.urlsafe() to be explicit and then ndb.Key(urlsafe=value) to create the new key. Unfortunately the best you can do with db is str(key) and db.Key(string_value).

Using key.id() also depends on ndb or db. If you are using db you know this value will be an integer (and that key.name() will be a string) but if you are using ndb it could be either an integer or a string. In that case, you should use key.integer_id() or key.string_id(). In either case, if you turn integers into strings, this will require manually casting back to an integer before retrieving entities or setting keys; e.g. MyModel.get_by_id(int(value))

If I were to make a recommendation, I would advise you to be explicit about your IDs, pay attention to the way they are allocated and give these opaque values to the user in the API. If you want to let App Engine allocate IDs for you use protorpc.messages.IntegerField to represent these rather than casting to a string.

Also, PLEASE switch from db to ndb if you haven't already.

Upvotes: 3

Related Questions