提问人:gau000 提问时间:11/16/2023 更新时间:11/16/2023 访问量:19
SQLAlchemy ORM - 如何表示视图和另一个表之间的 n 到 n 关系
SQLAlchemy ORM - how to represent n to n relationship between a view and another table
问:
我使用 postgresql 和 sqlalchemy 2
我有一个物化视图和两个表。
具体化视图是具有相同“形状”的两个表的并集
下面是伪代码中的物化视图
table1(id, name, surname)
table2(id, name, surname)
materialized_view as
select
'T1' AS source,
*
from table1
UNION
select
'T2' AS source,
*
from table2
我还有另外两个表保存与 table1 或 table2 行关联的标记
在伪代码中
tags(id, name)
tags_association(
id,
fk_tag fk to tags.id,
fk_table1 fk to table1.id nullable,
fk_table2 fk to table2.id nullable
)
-- tags_association have a constraint being xor fk_table1 fk_table2 (an association have either reference to table1 or table2, not both, not none)
我使用 sqlalchemy orm 在我的应用程序中表示。materialized_view
class Table1(db.Model):
...
class Table2(db.Model):
...
class Tags(db.Model):
...
class TagsAssociation(db.Model):
...
class MaterializedView(db.Model):
__tablename__ = "materialized_view"
source = Column(String)
id = Column(Integer)
name = Column(String)
surname = Column(Integer)
我能够用我的类执行查询。但是,我希望sqlalchemy执行必要的联接以检索与行相关的标签。MaterializedView
在伪代码中
class MaterializedView(db.Model):
__tablename__ = "materialized_view"
id = Column(Integer, primary_key=True)
name = Column(String)
surname = Column(Integer)
tags = relationship(
"Tags",
... # tell sqlalchemy how to perform the join
)
答: 暂无答案
评论