pythongoogle-app-enginegoogle-cloud-endpointsendpoints-proto-datastore

GAE NDB with Endpoints Proto Datastore: How to format response fields of reference property?


I have parent-child relationships in DataStore model: Building entity with reference entity to Office. I perform query on Building model and I would like to limit fields of Office entity in JSON response. Here is my code:

@Building.query_method(collection_fields=('id', 'name', 'office'), path='buildings', name='list')
def List(self, query):
    return query

collection_fields attribute works great only to define parent entity fields (Building), but how to limit fields of child entity?

Here is my response message in JSON:

  {  id : 5
    name : 'building name'
    office: {
        name: 'office name',
        field1 : 'test',
        field1 : 'test',
        field1 : 'test'
    }
}

I would like to remove some fields from Office object (i.e field1,field2 etc) to reduce JSON response size. Define limited_message_fields_schema of Office object is not good solution, because it works globally. I would like to format only this single query.


Solution

  • You can create EndpointsAliasProperty in the Building model, where you can transform self.office and use that value in collection_fields:

    @EndpointsAliasProperty
    def office_ltd(self):
        limited = doSomethingWith(self.office)
        return limited
    
    @Building.query_method(collection_fields=('id', 'name', 'office_ltd'), 
                           path='buildings', name='list')
    def List(self, query):
        return query