0

假设我有以下模型:

class Customer(Model):
    __tablename__ = 'customer'
    id = Column(Integer())
    treatments = relationship('Treatment', back_populates='customer')
    shipments = relationship('Shipment', back_populates='customer')

class Treatment(Model):
    __tablename__ = 'treatment'
    customer_id = Column(Integer(), ForeignKey('customer.id'))
    customer = relationship('Customer', back_populates='treatments')
    treatment_date = Column(DateTime(), nullable=False)

class Shipment(Model):
    __tablename__ = 'shipment'
    customer_id = Column(Integer(), ForeignKey('customer.id'))
    customer = relationship('Customer', back_populates='shipments')
    ship_date = Column(DateTime(), nullable=False)

我希望能够将 Shipment.ship_date 默认为 Treatment.treatment_date 的前一天。换句话说,我想做以下事情:

customer = Customer()
treatment = Treatment(treatment_date="11/02/2017")
customer.treatments.append(treatment)
shipment = Shipment()
customer.shipments.append(shipment)
shipment.ship_date
# 11/01/2017

当它们通过方法动态设置时,如何根据关系设置默认值append


为了澄清,这是一个关于 SqlAlchemy 以及何时建立关系的问题。例如,我尝试了以下方法:

class Shipment(Model):
    # ...same set up as above
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.ship_date = self.customer.treatments[0].treatment_date - timedelta(1)

但这会引发 TypeError,因为 SqlAlchemy 尚未设置该self.customer字段。

4

1 回答 1

0

似乎 SQLAlchemy 直到模型被添加并提交到会话之后才配置关系。

customer.shipments.append(new_shipment)
customer.shipments # includes the new shipment
new_shipment.customer # None
session.add(customer)
session.commit()
new_shipment.customer # <Customer object>

虽然这很烦人,而且我不确定为什么 SQLAlchemy 在创建一侧时不填充双向关系,但可以通过手动设置双方的关系来解决。例如:

new_shipment = Shipment(customer=customer)
new_shipment.ship_date # 11/01/2017
customer.shipments.append(new_shipment)
于 2017-12-18T16:13:36.443 回答