Query on ReferenceProperty in Google App Engine
I have two entity kinds and one referring to other like:
class Entity1(db.Expando):
prop1=db.StringProperty()
prop2=db.StringProperty()
class Entity2(db.Expando):
prop3=db.ReferenceProperty(Entity1)
prop4=db.StringProperty()
Can I write a query like:
q=Entity2.all().filter("prop3.prop1 =",somevalue)
Here prop3 has a reference and will be referring to some entity of kind Entity1 and I want to know all those entities of kind Entity2 which开发者_StackOverflow社区 refer to those entities of Entity1 that have prop1 as somevalue.
In my example I first fetched the key for the referenceproperty to use as a filter for the query. Then you can do the filtering based on the key in a the same amounts of queries you found keys for.
An example:
The models:
class Order(db.Model):
waiter = db.ReferenceProperty(Waiter,required=True)
date=db.DateTimeProperty(required=True)
delivered=db.BooleanProperty(default=False)
class Waiter(db.Model):
firstname=db.StringProperty(required=True)
lastname=db.StringProperty(required=True)
uuid=db.StringProperty(required=True)
The web request function:
def get(self):
waiteruuid=self.request.get("waiter")
q=Waiter.all()
q.filter('uuid =', waiteruuid)
waiterkey=q.get()
result={}
result['orders']=[]
q=Order.all()
if waiteruuid:
q.filter('waiter =', waiterkey)
orders=q.run()
Google Datastore doesn't support joins. You can fetch all the entites of Entity2 and does some manipulation to achieve what you have said.Somewhat similar to what @Mani suggested. But you can do it like
entities2 = Entity2.all()
for entity2 in entities2:
Entity1= entity.prop3.get()
if Entity1.prop1== somevalue:
#Do your processing here
Define Entity 2 as:
class Entity2(db.Expando):
entity_1_ref = db.ReferenceProperty(Entity1, collection_name = "set_of_entity_2_elements")
prop4=db.StringProperty()
This defines a collection name which can be operated from the other side of reference. (Entity1 in this case). I have taken the liberty to rename prop3 as something more appropriate.
Now you can do q = entity_1_object.set_of_entity_2_elements
(a new property for all your Entity1 objects) which will give you the results you want.
For more information, read this article indepth: http://code.google.com/appengine/articles/modeling.html
Update: Sorry, I got it wrong. The above suggestion doesnt get only those elements with entity_1_object.prop1 == somevalue
You can still get it in a round about way as follows:
for obj in q:
if ( obj.prop1 == somevalue):
# Do your processing here
or
for obj in q:
if ( obj.prop1 != somevalue):
# Delete this object from the list 'q'
But obviously this is not the best way. Lets wait for a better answer!
精彩评论