我正在使用 sqlalchemy 构建数据库,我想测试我的模型。即使我阅读了一些主题并浏览了文档,我也不确定我是否了解如何将数据加载到关联表中。我以这种方式创建了两个类:
class Instance(Base):
__tablename__ = 'Instances'
id = Column(Integer, primary_key=True)
url = Column(String, nullable=False)
env = Column(String(3), nullable=False)
code = Column(String, nullable=False)
customer = relationship('CustomerInstance', back_populates='instance')
class Customer(Base):
__tablename__ = "Customers"
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
code = Column(String, nullable=False)
instance = relationship('CustomerInstance', back_populates='customer')
class CustomerInstance(Base):
__tablename__='Customers_Instances'
customer_id = Column(Integer, ForeignKey('Customers.id'), primary_key=True)
instance_id = Column(Integer, ForeignKey('Instances.id'), primary_key=True)
instance = relationship('Instance', back_populates='customer')
customer = relationship('Customer', back_populates='instance')
然后我创建我的会话并刷新它:
session = Session()
session.add_all([
Instance(url='www.web.com', env='prd', code='123'),
Instance(url='www.123.com', env='prd', code='321'),
Instance(url='www.qwe.com', env='prd', code='345'),
Instance(url='www.rty.com', env='prd', code='678'),
Instance(url='www.hello.com', env='tes', code='098'),
Instance(url='www.hi.com', env='uat', code='567'),
Customer(name='ABC', code='567'),
Customer(name='DEF', code='000'),
Customer(name='GHI', code='123'),
Customer(name='KLM', code='456')
])
session.commit()
现在我如何填充对象/表CustomerInstance
,因为它仅由 2 个 ID 组成?我走对了吗?同样的问题,如何将数据注入到 primary_key 是 FK 的表中?