使用Flask / SQLAlchemy使用嵌套对象修补资源

时间:2018-05-29 22:49:25

标签: 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(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"
    }
}

这会创建一个新作者和新书。

但是,当我尝试使用类似的有效负载(同一作者,不同的书名)进行PATCH时,如

{
    "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 (完整demo source is here

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

0 个答案:

没有答案