如何解决使用 SQLAlchemy 和 Marshmallow 缺失字段的多对多关系?
快速前言:我对 SQLAlchemy 和 Marshmallow 都很陌生。
我目前有一个用 SQLAlchemy 编写的多对多关系,如下所示:
from sqlalchemy import Column,String,Integer,ForeignKey
from sqlalchemy.orm import relationship
from classes.base import Base
class DashboardCollection(Base):
__tablename__ = 'dashboard_collection'
id = Column(Integer,primary_key=True)
dashboard_id = Column(Integer,ForeignKey('dashboard.id'))
data_collection_id = Column(Integer,ForeignKey('collection.id'))
dashboard = relationship('Dashboard',back_populates="collections")
collection = relationship('Collection',back_populates="dashboards")
class Dashboard(Base):
__tablename__ = 'dashboard'
id = Column(Integer,primary_key=True)
name = Column(String(50))
dashboard_id = Column(String(36),nullable=False,unique=True)
collections = relationship('DashboardCollection',back_populates='dashboard')
class Collection(Base):
__tablename__ = 'collection'
id = Column(Integer,primary_key=True)
name = Column(String(50),unique=True)
dashboards = relationship('DashboardCollection',back_populates='collection')
我有 2 个表,Dashboard 和 Collection,以及一个关联表 DashboardCollection。这一切都存在于 1 个文件中。
然后我有 2 个棉花糖模式:
from marshmallow import Schema,fields
class DashboardSchema(Schema):
id = fields.Int()
name = fields.Str()
dashboard_id = fields.Str()
collections = fields.Nested(lambda: CollectionSchema(exclude=("dashboards",)),many=True)
class CollectionSchema(Schema):
id = fields.Int()
name = fields.Str()
dashboards = fields.Nested(DashboardSchema,exclude=("collections",),many=True)
在我的 python 代码中,然后我查询我的数据库/使用这样的模式:
dashboards_schema = DashboardSchema(many=True)
dashboards = session.query(Dashboard).all()
ret = dashboard_schema.dump(dashboards)
dashboards
打印:
[<Dashboard (id)='1',(name)='test',dashboard_id='a09dwa5-3263-4bdw-af8b-ddf6ecdwa148'>,<Dashboard (id)='2',(name)='cummins-web-test',dashboard_id='717sqb6-dwad9-4e29-bwa1-abbe2ddwda65'>]
ret
打印:
[{'dashboard_id': 'a09dwa5-3263-4bdw-af8b-ddf6ecdwa148','collections': [{'id': 1}],'id': 1,'name': 'test'},{'dashboard_id': '717sqb6-dwad9-4e29-bwa1-abbe2ddwda65','collections': [],'id': 2,'name': 'cummins-web-test'}]
DataCollection 表中有 1 行: |id|dashboard_id|collection_id| |-|-|-| |1| 1|1|
和 Collection 表中的 1 行: |身份证|姓名| |-|-| |1|一些名字|
我的问题是,为什么集合的 id 是嵌套列表中唯一显示的内容?我希望集合名称属性也出现。我尝试使用 only 而不是 exclude 或 fields.List() 而不是 many 的棉花糖模式的许多变体,但仍然没有变化。谢谢!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。