rest_gae icon indicating copy to clipboard operation
rest_gae copied to clipboard

GET request response with Foreign Key Property(Name, etc.) instead of key

Open get2abhi opened this issue 10 years ago • 2 comments

I have the following models

class Plant(ndb.Model):
    name = ndb.StringProperty()
    company = ndb.KeyProperty(kind='Company')
    owner = ndb.KeyProperty(kind='User')
    class RESTMeta:
        user_owner_property = 'owner'
        include_output_properties = ['name']

class Department(ndb.Model):
    name = ndb.StringProperty()
    plant = ndb.KeyProperty(kind='Plant')
    owner = ndb.KeyProperty(kind='User')
    class RESTMeta:
        user_owner_property = 'owner'
        include_output_properties = ['name']

Now in the GET request for department is working fine and the output is

/api/department

{
  "next_results_url": null,
  "results": [
    {
      "owner": null,
      "plant": "aghzfnBnLWFwaXISCxIFUGxhbnQYgICAgIDyiAkM",
      "name": "Packing",
      "id": "aghzfnBnLWFwaXIXCxIKRGVwYXJ0bWVudBiAgICAmc6UCQw"
    }
  ]
}

But how can i get the plant name instead of its Key

get2abhi avatar Mar 04 '16 08:03 get2abhi

The issue here is that we need to recursively decode the referenced object (plant in your case), but that's not always what the user wants. It's also problematic in case we have an endless recursion (e.g. two models that point to each other).

So we have 3 possible solutions at the moment:

  1. Use StructuredProperty (in your case, plant = ndb.StructuredProperty(Plant)). But that means that the Plant instance won't exist directly in the DB with its own key/ID (meaning, you won't be able to query for it directly).
  2. Do a second API call with the returned key for Plant (call GET /api/plant/<returned_key>).
  3. We implement in rest_gae recursive decoding of objects. However, we must make sure that - A) We won't do endless recursion of decoding models. B) We'll only decode models that have a specific flag turned on (e.g. using RESTMeta).

budowski avatar Mar 06 '16 00:03 budowski

The 3rd option looks promising provided we take care of circular dependency in models.

Is it work in progress ?

get2abhi avatar Mar 06 '16 06:03 get2abhi