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

GAE NDB with Endpoints Proto Datastore: filter by ID of reference property


I created a model called Building with reference to a model called Office. I would like to filter Buildings by OfficeID in Proto REST Query (@Building.query_method ....)

Currently, I work with office_key property (need to enter Entity Key of Office), but I would like to filter by OfficeID property. Any ideas on how to do this?

Here's what I've tried so far:

class Building(EndpointsModel):
    _message_fields_schema = ('id', 'name', 'office')
    name = ndb.StringProperty(default=None, indexed=True)
    office_key = ndb.KeyProperty(kind=Office, required=False)

    def office_setter(self, value):
        self.office_key = ndb.Key('Office', value.id)

    @EndpointsAliasProperty(setter=office_setter, property_type=Office.ProtoModel())
    def office(self):
        return self.office_key.get()


class Office(EndpointsModel):
        _message_fields_schema = ('id', 'name', 'created_date')
        name = ndb.StringProperty(default=None, indexed=True)
        created_date = ndb.DateTimeProperty(auto_now_add=True)

@Building.query_method(query_fields=('limit', 'order', 'pageToken', 'office_key'), path='buildings', name='list')
    def List(self, query):
        return query

Solution

  • It appears that Building -> Office is a one to one relationship (conversely the relationship of office -> building is many to one.

    So you need to store the office id in the building as a cached property for querying.

    Then you can query for Buildings with a specific office id.

    Alternately query for all buildings that the key held in office_key == 'some office key')