我有一个项目,试图使用marshmallow-sqlalchemy包将JSON中的数据加载到Sqlalchemy数据库中。该模型与子模型包含一对多关系。
使用具有许多书籍的作者的经典示例:
class Book(Base):
__tablename__ = "book"
id = Column(Integer, primary_key=True)
title = Column(String(50))
author_id = Column(Integer, ForeignKey("author.id"), nullable=False)
author = relationship("Author", backref=backref("books"))
class Author(Base):
__tablename__ = "author"
id = Column(Integer, primary_key=True)
name = Column(String(250))
books = relationship("Author", back_populates="author")
class BookSchema(ModelSchema):
class Meta:
model = Book
sqla_session = Session
class AuthorSchema(ModelSchema):
class Meta:
model = Author
sqla_session = Session
books = fields.Nested(BookSchema, many=True)
输入的JSON是
{
"name": "Author A",
"books": [
{"title": "Book 1"},
{"title": "Book 2"}
]
}
当我尝试加载JSON时,请使用以下内容:
json_repr = {...}
author_schema = AuthorSchema()
obj_repr = author_schema.load(json_repr)
当它试图反序列化文档时说Book是一种不可散列的类型,这引发了一个异常。
发生了什么,我相信解串器正在尝试使用类似的东西来创建对象
obj = model(**data)
不适用于一对多关系,因为列表的实例需要append()
设置为Author.books属性。
我一直找不到在网络上任何地方都可以使用的示例,我所看到的每个示例似乎都在嵌套一个实例,而不是一个列表。有没有建议使用棉花糖sqlalchemy完成此操作的方法,还是应该恢复使用直接棉花糖包,并使用@post_load方法手动附加关系对象。
答案 0 :(得分:2)
我有与此旧帖子类似的问题。设法在稍微不同的Flask + SQLAlchemy + Marshmallow-SQLAlchemy(版本2)框架下修复此帖子。发布代码以防万一。
大多数更改是models.py
books = relationship("Book", back_populates="author")
行back_populates
时使用backref
而不是sqlalchemy.exc.ArgumentError: Error creating backref 'books' on relationship 'Book.author': property of that name exists on mapper 'mapped class Author->author
models.py
class Book(db.Model):
__tablename__ = "book"
id = Column(db.Integer, primary_key=True)
title = Column(db.String(50))
author_id = Column(db.Integer, db.ForeignKey("author.id"), nullable=False)
author = relationship("Author", back_populates="books")
class Author(db.Model):
__tablename__ = "author"
id = Column(db.Integer, primary_key=True)
name = Column(db.String(250))
books = relationship("Book", back_populates="author")
schemas.py-大致相同
class BookSchema(ModelSchema):
class Meta:
model = Book
sqla_session = db.session
class AuthorSchema(ModelSchema):
class Meta:
model = Author
sqla_session = db.session
books = fields.Nested(BookSchema, many=True)
views.py
@api.route('/author/', methods=['POST'])
def new_author():
schema = AuthorSchema()
author = schema.load(request.get_json())
db.session.add(author.data) # version 2 marshmallow
db.session.commit()
return jsonify({"success": True})
答案 1 :(得分:1)
一种解决方法似乎是在sqlalchemy模型上添加一个初始化程序,该初始化程序显式地追加到集合中
class Author(Model):
__tablename__ = "author"
def __init__(self, books=None, *args, **kwargs):
super(Author, self).__init__(*args, **kwargs)
books = books or []
for book in books:
self.books.append(book)
尽管仍然有更好的解决方案,仍然感到好奇。