Python 使用Flask/SQLAlchemy使用嵌套对象修补资源
我有以下设置:Python 使用Flask/SQLAlchemy使用嵌套对象修补资源,python,flask-sqlalchemy,json-api,marshmallow,flask-restless,Python,Flask Sqlalchemy,Json Api,Marshmallow,Flask Restless,我有以下设置: # models class Author(BaseModel): id = Column(Integer, primary_key=True) first_name = Column(String(64)) last_name = Column(String(64)) class Book(db.Model): id = Column(Integer, primary_key=True) title = Column(String(6
# models
class Author(BaseModel):
id = Column(Integer, primary_key=True)
first_name = Column(String(64))
last_name = Column(String(64))
class Book(db.Model):
id = Column(Integer, primary_key=True)
title = Column(String(64))
author_id = Column(Integer,
ForeignKey("author.id"), nullable=True)
author = relationship(Author,
backref=backref('books'))
# schema
class AuthorSchema(BaseSchema):
first_name = fields.Str()
last_name = fields.Str()
class Meta(BaseSchema.Meta):
type_ = 'author'
model = Author
class BookSchema(BaseSchema):
title = fields.Str()
author_id = fields.Int()
author = fields.Nested('flask_and_restless.schemas.AuthorSchema', many=False)
class Meta(BaseSchema.Meta):
type_ = 'book'
model = Book
我可以使用以下有效负载发布一本包含嵌套作者的书:
{
"data": {
"attributes": {
"author": {
"data": {
"attributes": {
"first_name": "author 2",
"last_name": "last 2"
},
"type": "author"
}
},
"title": "my new title"
},
"type": "book"
}
}
这将与新书一起创建一位新作者
但是,当我尝试使用类似的负载(同一作者,不同的书名)进行修补时,如
我得到:AttributeError:“dict”对象没有属性“\u sa\u instance\u state”
我的堆栈:
烧瓶炼金术,棉花糖,烧瓶不宁
(全文)
你知道如何解决这个问题吗?为什么你把
author
看作是一个属性,而不是有效载荷中的一种关系?根据您的模型author
是book
模型的关系,不是吗?我这样做是因为author
是book
中的嵌套对象。同时,author
的定义也意味着它是book
的一种关系,因此您是对的,但我不知道如果不先分别发布这两个对象,我将如何创建或修补这种关系。我很想听听您的想法,JSON API还不支持批处理操作。下一个版本有一个草案:将关系视为属性并不能解决这一限制。
{
"data": {
"attributes": {
"author": {
"data": {
"attributes": {
"first_name": "author 2",
"last_name": "last 2"
},
"type": "author"
}
},
"title": "updated title 3"
},
"id": "3",
"type": "book"
}
}