我无法在PostgreSQL数据库上用sqlalchemy ORM编写此SQL语句:
update "DisappearanceRange"
set vehicle_status_stop_id = vs_id from (
select id as vs_id, vehicle_id as vs_vehicle_id from "VehicleStatus"
where timestamp = to_timestamp('2019-03-25 13:02:49.042646', 'YYYY-MM-DD HH24:MI:SS.US')
) vs_last_timestamp
where vehicle_status_stop_id is null
and vehicle_provider = 'TIER'
and vehicle_id = vs_vehicle_id;
我现在正在这样做:
subquery = self.db_session.query(
VehicleStatus.id.label('vs_id'),
VehicleStatus.vehicle_id.label('vehicle_id')).filter(
VehicleStatus.timestamp == timestamp).subquery()
self.db_session.query(DisappearanceRange).filter(
DisappearanceRange.vehicle_provider == self.PROVIDER_ENUM,
DisappearanceRange.vehicle_status_stop_id.is_(None),
DisappearanceRange.vehicle_id == subquery.c.vehicle_id
).update({'vehicle_status_stop_id': subquery.c.vs_id})
我想我只是不知道如何从子查询中更新。完成后,我得到:sawarning: Evaluating non-mapped column expression.
我可以在没有ORM的情况下编写它,但是我希望与其余代码保持一致。
我找到了一个相关的post,但没有很好的答案。
这些是我的课程:
class Vehicle(Base):
__tablename__ = 'Vehicle'
id = Column(String(150), primary_key=True)
provider = Column(Enum(ProviderEnum), primary_key=True)
type = Column(Enum(VehicleTypeEnum), nullable=False)
class VehicleStatus(Base):
__tablename__ = 'VehicleStatus'
id = Column(Integer, primary_key=True)
vehicle_id = Column(String(150), nullable=False)
vehicle_provider = Column(Enum(ProviderEnum), nullable=False)
__table_args__ = (ForeignKeyConstraint(['vehicle_id', 'vehicle_provider'],
['Vehicle.id', 'Vehicle.provider']),
{})
latitude = Column(Float, nullable=False)
longitude = Column(Float, nullable=False)
energy_level = Column(Float, nullable=False)
provider_specific = Column(JSON, nullable=False)
timestamp = Column(TIMESTAMP, nullable=False, index=True)
class DisappearanceRange(Base):
__tablename__ = 'DisappearanceRange'
id = Column(Integer, primary_key=True)
vehicle_id = Column(String(150))
vehicle_provider = Column(Enum(ProviderEnum))
__table_args__ = (ForeignKeyConstraint(['vehicle_id', 'vehicle_provider'],
['Vehicle.id', 'Vehicle.provider']),
{})
vehicle_status_start_id = Column(Integer, ForeignKey('VehicleStatus.id'))
vehicle_status_stop_id = Column(Integer, ForeignKey('VehicleStatus.id'),
nullable=True)