我正在努力解决一些简单的问题,我想通过过滤关系类键来查找对象。
我有以下课程(简体):
Hub --has_many-> Room --has_many--> Sensor --has_many-->Measurement
简化版
class Hub(Base):
__tablename__ = 'hubs'
id = Column(Integer, primary_key=True,autoincrement=True)
hub_name = Column(String(120), primary_key=True)
rooms = relationship(ROOM_CL, backref="hub",lazy='dynamic')
class Room(Base):
__tablename__ = 'rooms'
id = Column(Integer, primary_key=True,autoincrement=True)
room_name = Column(String(120), primary_key=True)
hub_id = Column(Integer, ForeignKey(Hub.getTable()+'.id'), primary_key=True)
sensors = relationship(SENSOR_CL, backref="room",lazy='dynamic')
class Sensor(Base):
__tablename__ = 'sensors'
id = Column(Integer, primary_key=True,autoincrement=True)
sensor_name = Column(String(120), primary_key=True)
room_id = Column(Integer, ForeignKey(Room.getTable()+'.id'), primary_key=True)
measurements = relationship(MEAS_CL, backref="sensor",lazy='dynamic')
class Measurement(Base):
__tablename__ = 'measurements'
id = Column(Integer, primary_key=True,autoincrement=True)
date_time = Column(DateTime)
sensor_id = Column(Integer, ForeignKey(Sensor.getTable()+'.id'), primary_key=True)
value = Column(Float)
现在想像我已经获得
hub_name = 'Hub1'
room_name = 'livingroom'
sensor_name = 'pir1'
我想找到所需传感器的所有测量值。 我知道我可以分层:
mhub = self.sqlsession.query(Hub).filter(Hub.hub_name=='Hub1').first()
mroom = mhub.rooms.filter(Room.room_name=='livingroom').first()
msensor = mroom.sensors.filter(Sensor.sensor_name=='pir1').first()
mmeas = msensor.measurements
但这对我来说似乎是一个丑陋的解决方案。 由于我已经拥有所有主键,因此可以过滤
之类的东西mmeas = self.sqlsession.query(Measurement).filter(Sensor.sensor_name=='pir1',Room.room_name=='livingroom',Hub.hub_name=='Hub1').all()
尝试过,但是它给了我表格中的所有结果
我认为我在某个时候误解了这个概念,而且我做错了方法。 感谢您的帮助!