简体   繁体   中英

How to query ndb for all properties and include keyproperty values?

Started this week using Google App Engine with Python Endpoints. The goal is to query a entity and include all keyproperty values. The models:

class Person(EndpointsModel):
  _message_fields_schema = ('id', 'surname', 'lastname', 'created')
  surname = ndb.StringProperty(indexed=False)
  lastname = ndb.StringProperty(indexed=False)

class Magazine(EndpointsModel):
  _message_fields_schema = ('id', 'name')
  name = ndb.StringProperty(indexed=False)

class Subscription(EndpointsModel):
  _message_fields_schema = ('id', 'publication', 'person', 'amount')
  magazine = ndb.KeyProperty(kind=Magazine)
  person = ndb.KeyProperty(kind=Person)
  amount = ndb.IntegerProperty()

These models are queried by the following to retrieve all items:

@endpoints.api(name='subscription', version='v1', description='REST API for Subscriptions')
 class SubscriptionV1(remote.Service):
   @Subscription.query_method(path='subscriptions', name='subscriptions.list')
   def SubscriptionList(self, query):
     return query

The result is:

{
 "items": [
  {
   "created": "2015-02-13T09:40:22.514000",
   "id": "6225984592281600",
   "modified": "2015-02-13T09:40:22.514000",
   "magazine": "ahNkZXZ-YXZpYW4tc2xpY2UtODUwchgLEgtQdWJsaWNhdGlvbhiAgICAgND7CQw",
   "synced": false
  }
 ]
}

While I want it to be:

"magazine": {"id": 123456789123456789,
"name": "Tech magazine"}

Looked everywhere, but couldn't find a good query. How should the query be to get this result?

If i read your code right you use endpoints proto datastore which offers EndpointsAliasProperty . In your example you could use it to get the correct subscription: rename magazine to magazine_key and define a EndpointsAliasProperty in your model:

@EndpointsAliasProperty(property_type=Subscription.ProtoModel())
def magazine(self):
    if self.magazine_key != None:
        magazine = self.magazine_key.get()
        return magazine

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM