如何在Google AppEngine中进行反向引用?
我正在尝试访问一个在Google App Engine中通过db.ReferenceProperty链接的对象。以下是模型的代码:
class InquiryQuestion(db.Model):
inquiry_ref = db.ReferenceProperty(reference_class=GiftInquiry, required=True, collection_name="inquiry_ref")
我想用以下方式来访问它:
linkedObject = question.inquiry_ref
然后
linkedKey = linkedObject.key
但是这样不行。有人能帮我吗?
2 个回答
3
反向引用其实就是一个查询。你需要用fetch()或者get()来真正从数据存储中获取实体或实体们:
linkedObject = question.inquiry_ref.get()
这样就可以了。如果你预期反向引用会指向多个实体,那就用fetch()。
实际上,你的类的构造方式让这里的情况有点模糊,不太清楚到底发生了什么。
如果你有一个GiftInquiry实体,它会自动有一个叫inquiry_ref的属性,这个属性就是一个查询(就像我上面说的),它会返回所有InquiryQuestion实体,这些实体的inquiry_ref属性被设置为这个GiftInquiry的键。
另一方面,如果你有一个InquiryQuestion实体,想要获取它的inquiry_ref属性所指向的GiftInquiry实体,你可以这样做:
linkedObject = db.get(question.inquiry_ref)
因为inquiry_ref只是指向的GiftInquiry的键,但这技术上并不是反向引用。
可以查看一下关于ReferenceProperty和反向引用的解释,详细内容可以参考文档。
5
你的命名方式有点让人困惑。inquiry_ref既是你的ReferenceProperty名称,也是你的反向引用集合名称。所以当你用question.inquiry_ref时,它会给你一个GiftInquiry的Key对象,但如果你用question.inquiry_ref.inquiry_ref,就会得到一个经过筛选的Query对象,这个对象只包含InquiryQuestion实体。
假设我们有以下的领域模型,其中文章和评论之间是一对多的关系。
class Article(db.Model):
body = db.TextProperty()
class Comment(db.Model):
article = db.ReferenceProperty(Article)
body = db.TextProperty()
comment = Comment.all().get()
# The explicit reference from one comment to one article
# is represented by a Key object
article_key = comment.article
# which gets lazy-loaded to a Model instance by accessing a property
article_body = comment.article.body
# The implicit back-reference from one article to many comments
# is represented by a Query object
article_comments = comment.article.comment_set
# If the article only has one comment, this gives us a round trip
comment = comment.article.comment_set.all().get()