flask - 如何使模型烧瓶棉花糖_sqlalchemy反序列化相关对象
问题描述
我有这个代码:
import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker, relationship, backref
engine = sa.create_engine("sqlite:///:memory:")
session = scoped_session(sessionmaker(bind=engine))
Base = declarative_base()
class Author(Base):
__tablename__ = "authors"
id = sa.Column(sa.Integer, primary_key=True)
name = sa.Column(sa.String, nullable=False)
books = relationship("Book", backref=backref("author", lazy="joined"),
foreign_keys="Book.author_id", lazy="dynamic")
def __repr__(self):
return "<Author(name={self.name!r})>".format(self=self)
class Book(Base):
__tablename__ = "books"
id = sa.Column(sa.Integer, primary_key=True)
title = sa.Column(sa.String)
author_id = sa.Column(sa.Integer, sa.ForeignKey("authors.id"))
Base.metadata.create_all(engine)
from marshmallow_sqlalchemy import SQLAlchemySchema, auto_field, SQLAlchemyAutoSchema
class AuthorSchema(SQLAlchemyAutoSchema):
class Meta:
model = Author
load_instance = True # Optional: deserialize to model instances
# dump_only = ("id",)
include_fk = True
class BookSchema(SQLAlchemyAutoSchema):
class Meta:
model = Book
load_instance = True
# dump_only = ("id",)
include_fk = True
author = Author(name="Chuck Paluhniuk")
author_schema = AuthorSchema()
book = Book(title="Fight Club", author=author)
book_schema = BookSchema()
session.add(author)
session.add(book)
session.commit()
dump_data_author = author_schema.dump(author)
print(dump_data_author)
dump_data_book = book_schema.dump(book)
print(dump_data_book)
当我运行它打印的代码时:
{'id': 1, 'name': 'Chuck Paluhniuk'}
{'id': 1, 'author_id': 1, 'title': 'Fight Club'}
我想更改代码以使其打印:
{'id': 1, 'name': 'Chuck Paluhniuk', 'books': [{'id': 1, 'author_id': 1, 'title': 'Fight Club'}]}
{'id': 1, 'author_id': 1, 'title': 'Fight Club'}
我该怎么做?
我想控制反序列化相关对象。
我也对元数据中的一些其他设置感到好奇,例如 load_only 和 dump_only 和 excelude 等。
解决方案
在我看来,有必要定义嵌套字段以便以这种方式在输出中包含关系。您可以定义自动包含关系,但这仅适用于主键。为了不使用字段的覆盖,我没有包含关系。
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from marshmallow_sqlalchemy import SQLAlchemyAutoSchema
from flask_marshmallow import Marshmallow
app = Flask(__name__)
db = SQLAlchemy(app)
ma = Marshmallow(app)
class Author(db.Model):
__tablename__ = "authors"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, nullable=False)
books = db.relationship("Book",
backref=db.backref("author", lazy="joined"),
foreign_keys="Book.author_id",
lazy="dynamic"
)
class Book(db.Model):
__tablename__ = "books"
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String)
author_id = db.Column(db.Integer, db.ForeignKey("authors.id"))
class BookSchema(SQLAlchemyAutoSchema):
class Meta:
model = Book
include_fk = True
load_instance = True
sqla_session = db.session
class AuthorSchema(SQLAlchemyAutoSchema):
class Meta:
model = Author
load_instance = True
# include_relationships = True # See below
sqla_session = db.session
books = ma.Nested(BookSchema, many=True)
with app.app_context():
db.drop_all()
db.create_all()
author = Author(name="Chuck Paluhniuk")
book = Book(title="Fight Club", author=author)
db.session.add(author)
db.session.add(book)
db.session.commit()
author_schema = AuthorSchema()
book_schema = BookSchema()
dump_data_author = author_schema.dump(author)
print(dump_data_author)
dump_data_book = book_schema.dump(book)
print(dump_data_book)
json = [
{'author_id': 1, 'title': 'Fight Club', 'id': 1}
]
schema = BookSchema(many=True)
print(schema.load(json))
json = [
{'books': [{'author_id': 1, 'title': 'Fight Club', 'id': 1}], 'name': 'Chuck Paluhniuk', 'id': 1}
]
schema = AuthorSchema(many=True)
print(schema.load(json))
推荐阅读
- excel - 时间值被复制粘贴为小数
- python - 任何数字的数字总和,直到总和为一位数
- python-3.x - python3将SQL响应从行格式化为字符串
- android - 在 Flutter Web 和移动应用中使用 Firebase
- google-analytics - Google Analytics 差异 - 不包括 IP 地址
- node.js - 节点 net.Socket 向所有连接的客户端发送数据
- python - 如何为没有属性的 div 内的节点进行 XPath
- udp - 提升 UDP 服务器
- javascript - Puppeteer:在相同的选择器中替换 innerHTML
- flutter - 如何使用flutter App为Eos帐户随机生成公钥和私钥