简体   繁体   English

如何基于SqlAlchemy关系设置模型默认值?

[英]How can I set model defaults based on a SqlAlchemy relationship?

Let's say I have the following models: 假设我有以下模型:

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)

I would like to be able to default the Shipment.ship_date to be the day before the Treatment.treatment_date. 我希望能够将Shipment.ship_date默认设置为Treatment.treatment_date的前一天。 In other words, I want to do the following: 换句话说,我要执行以下操作:

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

How do I set defaults based on relationships when they're set dynamically by methods like append ? 当通过诸如append类的方法动态设置默认值时,如何根据默认值设置默认值?


For clarification, this is a question about SqlAlchemy and when relationships are set up. 为了澄清起见,这是关于SqlAlchemy以及何时建立关系的问题。 For example, I've tried the following: 例如,我尝试了以下方法:

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)

But that throws a TypeError because SqlAlchemy hasn't set up the self.customer field yet. 但这会引发TypeError,因为SqlAlchemy尚未设置self.customer字段。

It appears as though SQLAlchemy does not configure relationships both ways until after the model has been added and committed to the session. 似乎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>

While this is annoying and I'm not sure why SQLAlchemy doesn't populate the two-way relationship when one side is created, it can be resolved by manually setting the relationship on both sides. 虽然这很烦人,而且我不确定为什么在创建一侧时SQLAlchemy不会填充双向关系,但是可以通过手动设置两侧的关系来解决。 For example: 例如:

new_shipment = Shipment(customer=customer)
new_shipment.ship_date # 11/01/2017
customer.shipments.append(new_shipment)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM