假设我有以下模型:
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
字段。