Python 如何在Google AppEngine上进行反向引用?

Python 如何在Google AppEngine上进行反向引用?,python,google-app-engine,web-applications,Python,Google App Engine,Web Applications,我正在尝试访问由Google app engine中的db.ReferenceProperty链接到的对象。以下是模型的代码: class InquiryQuestion(db.Model): inquiry_ref = db.ReferenceProperty(reference_class=GiftInquiry, required=True, collection_name="inquiry_ref") 我正试图通过以下方式访问它: linkedObject = question

我正在尝试访问由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

但它不起作用。有人能帮忙吗?

后面的参考资料只是一个查询。您需要使用fetch()或get()从数据存储中实际检索实体:

linkedObject = question.inquiry_ref.get()
我们应该做到这一点。或者,如果希望back ref引用多个实体,则可以使用fetch()

实际上,您的类的构造方式使得这里到底发生了什么变得模棱两可

如果您有一个GiftInquiry实体,它将获得一个名为inquiry\u ref的自动属性,该属性将是一个查询(如上所述),它将返回所有InquiryQuestion实体,这些实体的inquiry\u ref属性设置为该GiftInquiry的键

另一方面,如果您有一个InquiryQuestion实体,并且希望获取其inquiry\u ref属性设置到的GiftInquiry实体,则可以执行以下操作:

linkedObject = db.get(question.inquiry_ref)
因为查询只是所指礼物需求的关键,但从技术上讲,这不是一个反向参考


查看中的ReferenceProperty和back references的解释。

您的命名约定有点混乱。inquiry\u ref是您的ReferenceProperty名称和反向引用集合名称,因此question.inquiry\u ref为您提供一个GiftInquiry键对象,但question.inquiry\u ref.inquiry\u ref为您提供一个过滤到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()

我尝试了上面的方法:linkedObject=question.inquiry\u ref.get(),但在我的日志中出现了以下错误:get()只接受2个参数(1个给定)回溯(最近一次调用):File“/base/python\u runtime/python\u lib/versions/1/google/appengine/ext/webapp/u init\u.py”,第513行,在call handler.post(*groups)中文件“/base/data/home/apps/chowbird/1.342412733116965934/actions.py”,第126行,在post linkedObject=question.inquiry_ref.get()类型错误:get()只接受2个参数(给定1个),问题的类型是什么。这是一个好奇的问题还是一件礼物?我认为您可能需要使用第二种形式:linkedObject=db.get(question.inquirery\u ref)。