我有这个代码:
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 等。