插入前访问SQLAlchemy关系

时间:2015-02-05 00:08:53

标签: python sqlalchemy

我正在实例化一个新的SQLAlchemy对象,我无意将其保存到数据库中。但是,我希望能够在实例化之后查看它的关系属性。

class Alert(Base):
    __tablename__ = 'alert'
    alert_id = Column(Integer, primary_key=True)
    alert_code = Column(CHAR(1), ForeignKey('alert_code_desc.alert_code'))
    alert_description = relationship('AlertCodeDescription')

class AlertCodeDescription (Base):
    __tablename__ = 'alert_code_desc'
    alert_code = Column(CHAR(1), primary_key=True)
    alert_description = Column(String)
new_alert = Alert(**data)
alert_description = new_alert.alert_description.alert_description  #this causes an error

有没有办法填充关系中的数据,还是我必须以其他方式查询该数据?

1 个答案:

答案 0 :(得分:0)

这是与Can I use SQLAlchemy relationships in ORM event callbacks? Always get None非常相似的问题,答案相同。

手动创建对象时,SQLAlchemy不会自动设置关系。如果要在事件回调中访问alert_description,请在创建Alert实例时设置它:

ad = AlertCodeDescription(alert_code='A', alert_description='something')
a1 = Alert(alert_code=ad.alert_code)
db.session.add(a1)
db.session.commit()

assert a1.alert_description is None

# Here: set the relationship object, instead of the foreign key
a2 = Alert(alert_description=ad)
db.session.add(a2)
db.session.commit()

assert a2.alert_description == ad
assert a2.alert_code == ad.alert_code
相关问题