问题
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.
回答1:
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.
回答2:
Seems like you have more options here than sorting on your own. You could create a unique key_name for each of your categories, for instance "Bronco" or go with a unique created key "8HJ876KKL" (perhaps created by uuid). Then in the Car entity you can have a StringProperty with the key_name of the category. You could make this a StringListProperty if you want cars to belong to more than one category. You can then query on the category by key_name.
Another option is to use a ReferenceProperty in Car to point to Category object. Then you can query over the exact key when finding every Car that belongs to a category.
I am not sure how efficient queries are over ReferenceProperty vs StringProperty vs StringListProperty.
来源:https://stackoverflow.com/questions/6554159/google-app-engine-query-only-for-a-field