Search code examples
pythongoogle-app-enginegqlquery

Google app engine - Query only for a field


Note: this example is just representative of the problem, not a real use case

I would like to know if I have a certain objects for example Car and CarCategory:

Owner
     - name
     - age

Car 
     - name
     - brand
     - category( reference )
     - owner ( reference )

CarCategory
     - name
     - property

Can I query for a certain field?

For example CarCategory:

query = GqlQuery("SELECT category FROM Car")

I'm getting this error: BadQueryError: Parse Error: Expected no additional symbols at symbol Car

Update: What if want to have a list of all the categories owned by a certain user

I would like to do it in the most efficient possible way.


Solution

  • You can't query on individual fields in the App Engine datastore. Entities are stored and retrieved as serialized Protocol Buffers in their entirety, so there's no way to retrieve only certain fields.

    Given the db.Model abstraction, there'd be no sensible way to represent the returned data, either - you can't simply provide a model with only some fields filled in, as that might violate constraints, and would definitely cause trouble if you tried to store it back to the datastore!

    In response to your update: This would traditionally require a join and an aggregate, neither of which are supported on App Engine. Your best option is to query for and retrieve all a user's Car entities, and categorize by Category property yourself.