【发布时间】:2023-04-07 02:36:01
【问题描述】:
在使用 marshmallow-sqlalchemy 和 Flask-SQLAlchemy 时,在我的烧瓶应用程序中使用嵌套字段没有问题。现在我已经从 Flask-SQLAlchemy 切换到 SQLAlchemy(出于一些不相关的原因),我的嵌套字段不再显示任何数据。我觉得这可能与 SQLAlchemy Session 未传递到嵌套字段有关。
我的项目如下所示:
engine = create_engine(config.SQLALCHEMY_DATABASE_URI, echo=True)
Session = orm.scoped_session(orm.sessionmaker())
Session.configure(bind=engine)
Base = declarative_base(bind=engine)
class PodcastModel(Base):
__tablename__ = 'podcasts'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100))
host = db.Column(db.String(80))
episodes = relationship(EpisodeModel, backref='episode', lazy='dynamic')
@classmethod
def dump(cls, podcast):
podcast_schema = PodcastSchemaNested()
podcast_output = podcast_schema.dump(podcast).data
return podcast_output
class EpisodeModel(Base):
__tablename__ = 'episodes'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(200))
length = db.Column(db.Float(precision=2))
podcast_id = db.Column(db.Integer, db.ForeignKey('podcasts.id', ondelete='CASCADE'))
class BaseSchema(ModelSchema):
class Meta:
sqla_session = Session
ordered = True
class PodcastSchemaNested(BaseSchema):
id = fields.Integer()
name = fields.Str()
host = fields.Str()
episodes = fields.Nested('EpisodeSchema', many=True)
class EpisodeSchema(BaseSchema):
id = fields.Integer()
name = fields.Str()
length = fields.Float()
而json输出如下:
{
"id": 1,
"name": "Podcast Name",
"host": "Podcast Host",
"episodes": [
]
}
我已经在这个问题上苦苦挣扎了几个小时,并且非常感谢任何关于为什么嵌套字段不显示任何数据的输入。谢谢!
【问题讨论】: