Many-to-many relationship modeling in google app e

2019-07-27 22:47发布

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

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

1条回答
▲ chillily
2楼-- · 2019-07-27 23:18

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.

查看更多
登录 后发表回答