【问题标题】:How to do a back-reference on Google AppEngine?如何在 Google AppEngine 上进行反向引用?
【发布时间】:2011-02-27 10:26:26
【问题描述】:

我正在尝试访问由 Google 应用引擎中的 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

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

【问题讨论】:

    标签: python google-app-engine web-applications


    【解决方案1】:

    您的命名约定有点混乱。 query_ref 既是您的 ReferenceProperty 名称又是您的反向引用集合名称,因此 question.inquiry_ref 为您提供 GiftInquiry Key 对象,但 question.inquiry_ref.inquiry_ref 为您提供过滤到 InquiryQuestion 实体的 Query 对象。

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

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

    【讨论】:

      【解决方案2】:

      反向引用只是一个查询。您需要使用 fetch() 或 get() 从数据存储区实际检索实体:

      linkedObject = question.inquiry_ref.get()
      

      应该可以解决问题。或者,如果您希望后面的 ref 引用多个实体,则可以使用 fetch()。

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

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

      另一方面,如果您有一个 InquiryQuestion 实体,并且您想要获取为其设置了inquiry_ref 属性的 GiftInquiry 实体,您可以这样做:

      linkedObject = db.get(question.inquiry_ref)
      

      因为inquiry_ref 只是被引用的GiftInquiry 的Key,但从技术上讲这不是BackReference。

      查看 ReferenceProperty 的解释以及来自 the docs 的反向引用。

      【讨论】:

      • 我尝试了上述方法:linkedObject = question.inquiry_ref.get() 我在日志中收到以下错误:get() 正好需要 2 个参数(给定 1 个) Traceback(最近一次调用最后一次) :文件“/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py”,第 513 行,在 call handler.post(*groups) 文件“/base /data/home/apps/chowbird/1.342412733116965934/actions.py",第 126 行,在文章 linkedObject = question.inquiry_ref.get() 类型错误:get() 只需要 2 个参数(1 个给定)
      • 什么是问题类型。是 InquiryQuestion 还是 GiftInquiry?我认为您可能想使用第二种形式:linkedObject = db.get(question.inquiery_ref)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-13
      • 2012-10-30
      • 2016-10-04
      • 2011-02-20
      • 1970-01-01
      • 2014-11-22
      • 1970-01-01
      相关资源
      最近更新 更多