PATCHing resources with nested objects with Flask/

2019-07-14 20:11发布

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?

0条回答
登录 后发表回答