如何在googleappengine上进行反向引用?

2024-09-30 18:23:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图访问一个由数据库参考属性在谷歌应用引擎中。这是模型的代码:

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

我试图通过以下方式访问它:

^{pr2}$

然后呢

linkedKey = linkedObject.key

但它不起作用。谁能帮忙吗?在


Tags: 代码模型引擎ref数据库dbmodel属性
2条回答

你的命名约定有点混乱。inquiry_ref是您的ReferenceProperty名称和back reference集合名称,因此问题查询给你一个礼物钥匙,但是问题查询.inquiry_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()

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

linkedObject = question.inquiry_ref.get()

应该会成功的。或者,如果您希望back ref引用多个实体,则可以使用fetch()。在

实际上,你的类的构造方式使它对于这里到底发生了什么变得模棱两可。在

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

另一方面,如果您有一个InquiryQuestion实体,并且您想获取设置了其inquiry_ref属性的GiftInquiry实体,则可以执行以下操作:

^{pr2}$

因为问询只是被提及的礼物的关键,但从技术上讲,这不是回溯。在

the docs查看ReferenceProperty和反向引用的说明。在

相关问题 更多 >