谷歌应用程序引擎中的多对多关系建模 [英] Many-to-many relationship modeling in google app engine
问题描述
我遵循此处概述的内容。这里是我的代码:
I followed what is outlined here. Here is my code:
from google.appengine.api import users
from google.appengine.ext import db
class Book(db.Model):
title = db.StringProperty()
class Author(db.Model):
name = db.StringProperty()
class BookAuthor(db.Model):
book = db.ReferenceProperty(Book, required=True, collection_name='books')
author = db.ReferenceProperty(Author, required=True, collection_name='authors')
b = Book(title="My Book")
a = Author(name="Author of My Book")
db.put([b, a])
ba = BookAuthor(book=b, author=a)
ba.put()
b.authors
a.books
我得到AttributeError: 'Book'对象没有属性'authors'
and I get AttributeError: 'Book' object has no attribute 'authors'
推荐答案
ReferenceProperties 将查询对象添加为被引用类的属性。所以仔细看看你的映射:
ReferenceProperties add query-objects as attributes to the referenced class. So look carefully at your mappings:
class BookAuthor(db.Model):
# This adds a query-object as an attribute named 'books' to Book entities.
book = db.ReferenceProperty(Book, required=True, collection_name='books')
# This adds a query-object as an attribute named 'authors' to Author entities.
author = db.ReferenceProperty(Author, required=True, collection_name='authors')
在您的代码中:
In your code:
b = Book(title="My Book")
a = Author(name="Author of My Book")
因此, b
将具有书
属性,而不是作者
。并且, a
将具有作者
属性,而不是 books
。
So, b
would have a books
attribute, not authors
. And, a
would have a authors
attribute, not books
.
如果您更改集合名称,您的代码应该运行。
If you change the collection names, your code should run.
class BookAuthor(db.Model):
# This adds a query-object as an attribute named 'authors' to Book entities.
book = db.ReferenceProperty(Book, required=True, collection_name='authors')
# This adds a query-object as an attribute named 'books' to Author entities.
author = db.ReferenceProperty(Author, required=True, collection_name='books')
另外,如果 BookAuthor
没有其他属性,请确保查看引用的文章中列出的键列表方法。
Also, if BookAuthor
does not have additional properties, make sure you look at the list-of-keys method outlined in the article you referenced.
这篇关于谷歌应用程序引擎中的多对多关系建模的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!