1

我正在使用 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 的表中?

4

1 回答 1

1

通过 a 分配链接实例relationship或发出 aflush链接对象(刷新后,新创建对象的主键被填充)并手动分配 id。

例子

instance = CustomerInstance(
    instance=Instance(url='example.com', env='prd', code=123),
    customer=Customer(name='ABC', code='123'),
)
session.add(instance)

# SQLAlchemy will handle the foreign keys itself.
session.flush()

或者

instance = Instance(url='example.com', env='prd', code=123),
customer = Customer(name='ABC', code='123'),
session.add_all([instance, customer])
session.flush()

# Now the primary keys are populated!
cust_instance = CustomerInstance(
    customer_id=customer.id,
    instance_id=instance.id,
)
于 2017-02-16T14:26:44.657 回答