Many-to-many relationship modeling in google app engine

此生再无相见时 提交于 2019-12-11 08:46:10

问题


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:


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.



来源:https://stackoverflow.com/questions/4347671/many-to-many-relationship-modeling-in-google-app-engine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!