首页 > 解决方案 > 使用 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(完整的演示源在这里

任何想法如何解决这一问题?

标签: pythonflask-sqlalchemyjson-apimarshmallowflask-restless

解决方案


推荐阅读