Python 如何处理棉花糖sqlalchemy中的嵌套关系
我有一个项目,试图使用marshmallow Sqlalchemy包将JSON中的数据加载到Sqlalchemy数据库中。该模型包含与子模型的一对多关系 使用一位作家写了许多书的经典例子:Python 如何处理棉花糖sqlalchemy中的嵌套关系,python,sqlalchemy,marshmallow,Python,Sqlalchemy,Marshmallow,我有一个项目,试图使用marshmallow Sqlalchemy包将JSON中的数据加载到Sqlalchemy数据库中。该模型包含与子模型的一对多关系 使用一位作家写了许多书的经典例子: class Book(Base): __tablename__ = "book" id = Column(Integer, primary_key=True) title = Column(String(50)) author_id = Column(Integer, For
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)
当它试图反序列化该文档,说该书是一种不可损坏的类型时,它引发了一个异常
现在发生的情况是,我相信反序列化程序正在尝试使用
obj = model(**data)
这不适用于一对多关系,因为列表的实例需要append()
”添加到Author.books属性中
我在网上的任何地方都找不到这样的例子,我看到的每一个例子似乎都是嵌套在一个实例中,而不是列表中。有没有一种推荐的方法可以使用marshmallow sqlalchemy实现这一点,或者我应该恢复使用straight marshmallow包,并使用@post_load方法手动附加关系对象 处理这个问题的一种方法似乎是在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)
但仍然很好奇是否有更好的解决方案。我在这篇旧文章中遇到了类似的问题。设法在一个稍有不同的框架Flask+SQLAlchemy+MarshmallowSqlAlchemy(版本2)下修复了这篇文章。张贴代码以防有用 大多数更改都是针对
models.py
books=关系(“Book”,back_populates=“author”)
back\u填充而不是backref
,因为我得到错误sqlalchemy.exc.ArgumentError:在关系“Book.author”上创建backref“books”时出错:映射器的“映射类author->author”上存在该名称的属性
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})
你找到其他的方法了吗?