2010-12-03 90 views
1

我遵循了概述的here。這裏是我的代碼:谷歌應用引擎中的多對多關係建模

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的:「書」對象有沒有屬性「作者」

回答

2

ReferenceProperties添加query-objects的屬性中引用的類。所以,仔細看看你的映射:

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

在您的代碼:

b = Book(title="My Book") 
a = Author(name="Author of My Book") 

所以,b將有一個books屬性,而不是authors。而且,a將具有authors屬性,而不是books

如果更改集合名稱,應該運行您的代碼。

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沒有附加屬性,一定要看看你提到的文章中概述的列表的密鑰的方法。

+0

優秀!非常感謝你。 – marco 2010-12-03 18:59:34