pnmtu13894 pnmtu13894 - 2 months ago 10
Python Question

How to retrieve entities from Google Cloud Datastore

I have some problems with Cloud Datastore in Google App Engine.

I have 2 Models in the database which are:

class Product(ndb.Model):
name = StringProperty(required=True)
category = KeyProperty(kind=Category)
description = TextProperty(required=True)
price = IntegerProperty(required=True)


And

class Category(ndb.Model):
name=StringProperty(required=True)


So how can i get all the datas from Product Class that belong to a certain Category?

In Relational SQL i used:

SELECT * FROM Product WHERE category = 'CertainName';


Thank you!

Answer

The following should perform what your sql query is doing:

query = Product.query(Product.category == "CertainName") # Note the "=="

Edit:

I just realized you need to filter by key(thank you @mgilson). The query changes a little. Basically you just need to first get your category_entity and then apply the filter like this:

query = Product.query(Product.category == category_entity.key)

where, for example, you could fetch a category_entity like shown below:

category_entity = Category.query(Category.name == "SomeCat").fetch()

Refer to https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/appengine/standard/ndb/queries/snippets.py for more info (look at query_purchases_for_customer_via_key)