开发者

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()
开发者_JAVA技巧
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

and I get AttributeError: 'Book' object has no attribute 'authors'


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

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

Also, if BookAuthor does not have additional properties, make sure you look at the list-of-keys method outlined in the article you referenced.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜