2010-06-03 33 views
3

我试图访问一个由Google应用程序引擎中的db.ReferenceProperty链接的对象。下面是这个模型的代码:如何对Google AppEngine进行反向引用?

class InquiryQuestion(db.Model): 
    inquiry_ref = db.ReferenceProperty(reference_class=GiftInquiry, required=True, collection_name="inquiry_ref") 

,我试图访问它以下列方式:

linkedObject = question.inquiry_ref 

然后

linkedKey = linkedObject.key 

,但它不工作。任何人都可以帮忙吗?

回答

5

您的命名约定有点混乱。 inquiry_ref既是您的ReferenceProperty名称,也是您的后台引用收集名称,因此question.inquiry_ref会为您提供GiftInquiry Key对象,但question.inquiry_ref.inquiry_ref会为您提供过滤到InquiryQuestion实体的Query对象。

假设我们有以下领域模型,文章和评论之间具有一对多的关系。

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() 
3

反向引用只是一个查询。您需要使用取()或get()方法来实际从数据库中检索的实体:

linkedObject = question.inquiry_ref.get() 

应该做的伎俩。或者,如果您期待后端引用多个实体,则可以使用fetch()。

实际上,你的类的构造方式使得它在这里发生了什么是模糊的。

如果您有一个GiftInquiry实体,它将获得一个名为inquiry_ref的自动属性,该属性将成为查询(如上所述),该查询将返回其inquiry_ref属性设置为该GiftInquiry的密钥的所有InquiryQuestion实体。作为inquiry_ref只是

linkedObject = db.get(question.inquiry_ref) 

在另一方面,如果你有一个InquiryQuestion实体,并且你想获得到其inquiry_ref属性设置GiftInquiry实体,你可以这样做被引用的GiftInquiry的关键字,但这在技术上不是BackReference。

查看ReferenceProperty的解释和从the docs返回的参考文献。

+0

我试过上面: linkedObject = question.inquiry_ref.get() 而我在我的日志中的以下错误: 的get()到底需要2个参数(1给出) 回溯(最近调用最后一次): 文件 “/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py”,第513行,在__call__中 handler.post(* groups) File“/ base/data/home/apps/chowbird/1.342412733116965934/actions.py“,第126行,后 linkedObject = question.inquiry_ref.get() TypeError:get()只需要2个参数(给出1) – jCuga 2010-06-03 17:49:45

+0

问题的类型是什么。这是一个InquiryQuestion还是一个GiftInquiry?我认为你可能想要使用第二种形式:linkedObject = db.get(question.inquiery_ref)。 – 2010-06-03 17:51:17