PATCHing resources with nested objects with Flask/SQLAlchemy

感情迁移 提交于 2019-12-12 20:45:50

问题


I have the following setup:

# 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

I can POST a book with a nested author with this payload:

{
    "data": {
        "attributes": {
            "author": {
                "data": {
                    "attributes": {
                        "first_name": "author 2",
                        "last_name": "last 2"
                    },
                    "type": "author"
                }
            },
            "title": "my new title"
        },
        "type": "book"
    }
}

This creates a new author along with the new book.

However, when I try to PATCH with a similar payload (same author, different book title), as in

{
    "data": {
        "attributes": {
            "author": {
                "data": {
                    "attributes": {
                        "first_name": "author 2",
                        "last_name": "last 2"
                    },
                    "type": "author"
                }
            },
            "title": "updated title 3"
        },
        "id": "3",
        "type": "book"
    }
}

I get: AttributeError: 'dict' object has no attribute '_sa_instance_state'

My stack: Flask-SQLAlchemy, Marshmallow-JSONAPI, Flask-Restless (full demo source is here)

Any ideas how to fix this?

来源:https://stackoverflow.com/questions/50594051/patching-resources-with-nested-objects-with-flask-sqlalchemy

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