views:

44

answers:

2

Hi, I have two models like below:-

class Food(db.Model):
      foodname=db.StringProperty()
      cook=db.StringProperty()

class FoodReview(db.Model):
      thereview=db.StringProperty()
      reviews=db.ReferenceProperty(Food,collections_name='thefoodreviews')

I go ahead and create an entity:-

s=Food(foodname='apple',cook='Alice')`   
s.put()

When someone writes a review, the function which does the below comes in play:

theentitykey=db.Query(Food,keys_only=True).filter('foodname =','apple').get()
r=FoodReview()
r.reviews=theentitykey #this is the key of the entity retrieved above and stored as a ref property here
r.thereview='someones review' #someone writes a review
r.put()

Now the problem is how to retrieve these reviews. If I know the key of the entity, I can just do the below:-

theentityobject=db.get(food-key) # but then the issue is how to know the key
for elem in theentityobject.thefoodreviews:
       print elem.thereview

else I can do something like this:-

theentityobj=db.Query(Food).filter('foodname =','apple').get()

and then iterate as above, but are the above two ways the correct ones?

A: 

The second method looks exactly like what AppEngine tutorial advices. Seems like the right thing to do, if you want to find all reviews for a particular foodname.

Evgeny
+1  A: 

If to get the food you're always doing db.Query(Food).filter('foodname =','apple') then it looks like your foodname is your key... Why not just use it as a key_name?

Then, you can even fetch the reviews without fetching the food itself:

key = db.Key.from_path('food', 'apple')
reviews = FoodReview.all().filter("reviews =", key)
Eran Kampf
Thanks Eran! This definitely looks good and works fine too.
Alice