我有两个模型如下: -
class Food(db.Model):
foodname=db.StringProperty()
cook=db.StringProperty()
class FoodReview(db.Model):
thereview=db.StringProperty()
reviews=db.ReferenceProperty(Food,collections_name='thefoodreviews')
我继续创建一个实体: -
s=Food(foodname='apple',cook='Alice')`
s.put()
当有人撰写评论时,执行以下操作的功能将起作用:
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()
现在的问题是如何检索这些评论。如果我知道实体的密钥,我可以执行以下操作: -
theentityobject=db.get(food-key) # but then the issue is how to know the key
for elem in theentityobject.thefoodreviews:
print elem.thereview
否则我可以这样做: -
theentityobj=db.Query(Food).filter('foodname =','apple').get()
然后如上所述迭代,但上述两种方法是正确的吗?
答案 0 :(得分:1)
如果要获得食物你总是在做db.Query(食物).filter('foodname =','apple')那么看起来你的食物名称是你的关键...... 为什么不将它用作key_name?
然后,您甚至可以在不获取食物本身的情况下获取评论:
key = db.Key.from_path('food', 'apple')
reviews = FoodReview.all().filter("reviews =", key)
答案 1 :(得分:0)
第二种方法看起来与App Engine教程建议完全一样。 如果您想查找特定食品名称的所有评论,这似乎是正确的做法。