Sensor
有许多Reading
个,每个都有一个时间戳的值和类型。我想在Sensor
上创建一个属性,列出每种类型的最新值。我知道如何在SQL中获取它,但是如何使用SQLAlchemy构建它?
select * from (
select * from Readings
left join Sensors on Readings.SensorID = Sensors.SensorID
where Readings.SensorID = passed_id order by Timestamp desc
) as tmp group by ValueType;
class Reading(db.Model):
__tablename__ = 'Readings'
index = db.Column('id', db.Integer, primary_key=True)
sensor_id = db.Column('SensorID', db.Integer, db.ForeignKey('Sensors.SensorID'))
sensor_type = db.Column('SensorType', db.Integer)
timestamp = db.Column('Timestamp', db.DateTime)
value_type = db.Column('ValueType', db.Integer)
value = db.Column('Value', db.Float)
class Sensor(db.Model):
__tablename__ = 'Sensors'
index = db.Column('id', db.Integer, primary_key=True)
id = db.Column('SensorID', db.Integer, unique=True)
type = db.Column('SensorType', db.Integer)
location = db.Column('Location', db.String(50))
readings = db.relationship('Reading', backref='SensorID', lazy='dynamic')
答案 0 :(得分:0)
似乎我终于找到了解决方案。我在Sensor类中添加了以下内容:
rake db:migrate