使用sqlalchemy更新了相关模型

时间:2017-03-14 11:14:24

标签: python sqlalchemy

我有以下型号

class Alert(Base):
    __table_name__  = 'alerts'
    #fields left out for ease
    channel_id = Column(Integer)

class AlertStatus(Base):
    __table_args__ = (
        PrimaryKeyConstraint('id', name='pk_alert_state_change'),
        ForeignKeyConstraint(
            ['reason_id'],
            ['reasons.id'],
            name='fk_alert_status_change_reason_id__reasons'
        ),

        ForeignKeyConstraint(
            ['alert_id'],
            ['alerts.id'],
            name='fk_alert_status_change_alert_id__alert'
        ),

        UniqueConstraint(
            'alert_id', 'reason_id',
            name='ux_alert_status_change__alert_id__reason_id'
        )
    )
    #fields left out for ease

    status = Column(String)
    alert_id = Column(Integer)
    reason_id = Column(Integer)
    date = Column(UTCDateTime, default=utcnow_tzaware, onupdate=utcnow_tzaware) #UTCDateTime is just a custom column to return tz aware datetime objects. 

    alert = relationship('Alert' backref=backref('status', uselist=False)
    reason = relationship('Reason', backref='status')

我想使用特定的channel_id过滤提醒并更新其状态(但它不起作用)

session.query(Alert).filter(channel_id==3).update({AlertStatus.status:'newstatus', AlertStatus.reason_id:5})

但是我收到以下错误

CompileError: Unconsumed column names: status, reason_id

如何从对象中更新相关对象。

我也试过这个:

 db.get_session().query(models.AlertStatus).filter(
        Alert.channel_id == 3). \
        update({'status': 'newstatus',
                'reason_id': 5}, synchronize_session=False)

但我得到

OperationalError: (sqlite3.OperationalError) near "FROM": syntax error [SQL: u'UPDATE alerts_status SET reason_id=?, status=?, date=? FROM alerts WHERE alerts.channel_id = ?'] [parameters: (5, u'open', '2017-03-14 11:24:19.565573', 1)]

在sqlite inmemory db

中测试

0 个答案:

没有答案