python - 使用 Flask/SQLAlchemy 使用嵌套对象修补资源
问题描述
我有以下设置:
# 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"
}
}
这将与新书一起创建一个新作者。
但是,当我尝试使用类似的有效负载(相同的作者,不同的书名)修补时,如
{
"data": {
"attributes": {
"author": {
"data": {
"attributes": {
"first_name": "author 2",
"last_name": "last 2"
},
"type": "author"
}
},
"title": "updated title 3"
},
"id": "3",
"type": "book"
}
}
我得到:AttributeError: 'dict' object has no attribute '_sa_instance_state'
我的堆栈:Flask-SQLAlchemy、Marshmallow-JSONAPI、Flask-Restless(完整的演示源在这里)
任何想法如何解决这一问题?
解决方案
推荐阅读
- javascript - 初始化 jquery 插件时设置 scrollTop
- ehcache - 如何使用 EhCache3 在 Spring Boot 2 中从外部位置加载 ehCache.xml
- angular - 模块“ComponentsModule”声明的意外值“DecoratorFactory”
- python-3.x - 当在图像中找不到对象时,如何使 keras 模型在进行预测时不返回任何结果?
- osmnx - 是否有 OSMnx 函数来查找距地理编码地址最近的建筑物占地面积?
- c++ - 使用 sscanf 设置结构引用的值
- c# - C#多线程foreach循环
- php - 从另一个 PHP 文件访问变量
- java - 如何修复使用名称创建 bean 的错误?
- oracle10g - 我无法从客户端 PC 连接到 oracle 数据库