GoogleCloudPlatform / endpoints-proto-datastore

Apache License 2.0
154 stars 52 forks source link

suggestion: automagically `KeyProperty` -> `Entity` #126

Closed matantsu closed 9 years ago

matantsu commented 9 years ago

I have a model as such:

class B(EndpointsModel):
   something = ndb.StringProperty()

class A(EndpointsModel):
   B_list = ndb.KeyProperty(kind='B' , repeated=True)

when requesting the entity from the api i get:

"B_list": [
  "ahdkZXZ-d2F0ZXItcHJvamVjdC1kZWJ1Z3IWCxIJSG91c2VIb2xkGICAgICAgNAIDA",
  "ahdkZXZ-d2F0ZXItcHJvamVjdC1kZWJ1Z3IWCxIJSG91c2VIb2xkGICAgICAgNAKDA",
  "ahdkZXZ-d2F0ZXItcHJvamVjdC1kZWJ1Z3IWCxIJSG91c2VIb2xkGICAgICAgNAJDA"
 ]

as expected, but wouldn't it be awesome if it automatically converted the keys to entities like this:

"B_list": [
  {
      "something": "foo"
  },
  {
      "something": "bar"
  },
  {
      "something": "bazz"
  },
 ]
dhermes commented 9 years ago

So you're saying you want the actual entity retrieved?

That's not the point of a KeyProperty. A KeyProperty is to literally store a key. If you want to store another entity you can do so using ndb.StructuredProperty.

And that "automagic" would cost money every time the entity is retrieved, so it's something that should be explicitly requested rather than implicitly done for users.

UPDATE: See previous discussions about StructuredProperty.

matantsu commented 9 years ago

for server purposes using a KeyProperty is most efficient , but when a client retrieves the result from the api , it would be much more useful to give it the actual entity instead of a key , so it wouldn't have to access the api again to retreive the entity from the key.

of course i would put the choise in the hands of the developer.

dhermes commented 9 years ago

Ahh I see. I like the idea.

Check out the EndpointsAliasProperty. You can wrap a getter and use the persisted key to retrieve the entity in the getter. You'll probably want to use this in conjunction with _message_fields_schema.

In terms of speed of your API, you may find you would have rather persisted the entity rather than the key. (See @kamens post on The App Engine Way.) In particular:

Do lots of work when writing to make reads fast

Please re-open if you think this isn't useful.