如何根据SqlAlchemy关系设置模型默认值?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何根据SqlAlchemy关系设置模型默认值?相关的知识,希望对你有一定的参考价值。
假设我有以下型号:
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
如何通过qazxswpoi等方法动态设置默认值时,如何根据关系设置默认值?
为了澄清,这是关于SqlAlchemy以及何时建立关系的问题。例如,我尝试过以下方法:
append
但是抛出TypeError是因为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)
字段。
答案
似乎SQLAlchemy在模型添加并提交到会话之前不会双向配置关系。
self.customer
虽然这很烦人,但我不确定为什么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关系设置模型默认值?的主要内容,如果未能解决你的问题,请参考以下文章
您如何设置 sqlalchemy 关系ihp,以便子查询负载将根据属性过滤我们的结果
SQLAlchemy docs(设置列默认值) - 这行语法有效的python如何? [关闭]