使用SQLalchemy设置并插入多个关联表
我有多个相关的表,它们的结构像星形图,具体如下:
FACT TABLE
==========
id (primary key)
globalattribute1
globalattribute2
DIMENSION TABLE 1
==========
id (foreign key to fact_table.id)
specificattribute1
specificatrribute2
DIMENSION TABLE 2
==========
id (foreign key to fact_table.id)
specificattribute1
specificatrribute2
这是我目前在Python代码中写的内容(除了基础部分和会话部分)。你能给我一些建议吗?
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import *
engine = create_engine('mysql://...')
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base()
class Fact(Base):
__tablename__ = 'fact_table'
id = Column(Integer, primary_key=True)
global1 = Column(String(255))
global2 = Column(String(255))
#Constructor
class Dimension1(Base):
__tablename__ = 'dimension1'
id = Column(Integer, ForeignKey('fact_table.id'))
specific1 = Column(String(255))
specific2 = Column(String(255))
#Constructor
class Dimension2(Base):
__tablename__ = 'dimension2'
id = Column(Integer, ForeignKey('fact_table.id'))
specific1 = Column(String(255))
specific2 = Column(String(255))
#Constructor
Base.metadata.create_all(engine)
我该如何使用这些内容来插入一条记录,这条记录既包含全局属性,又包含某个维度表的特定属性呢?
1 个回答
2
如果我理解得没错,你是想让 Dimension1
和 Dimension2
和 Fact
之间有一对一的关系,对吧?如果是这样,你可以看看一对一关系的配置。
class Fact(Base):
...
dim1 = relationship('Dimension1', uselist=False)
dim2 = relationship('Dimension2', uselist=False)
#Constructor
另外,你可能还想了解一下关联代理。我自己没用过,但据我了解,它们可以直接指定一个外部属性,而不需要像这样去写 fact.dim1.specific1
。
希望这能解答你的问题。如果你不想要一对一的关系,可以看看其他可用的关系,看看哪个更合适。
要添加一个新的事实,可以这样做:
fact = Fact(...)
fact.dim1 = Dimension1(...)
fact.dim2 = Dimension2(...)
session.add(fact)
这样做会在 session.commit
时自动执行所有必要的查询(或者你用其他方式进行事务处理)。如果想了解更多细节,建议你再看看使用会话。