JAM.py飞机维护数据库:自动填充tach_in与累计飞行时间计算
针对JAM.py飞机维护数据库的解决方案
问题a:自动填充新记录的tach_in为上一条记录的tach_out
在飞行记录模型(示例命名为Flight)中添加before_insert钩子,在新记录插入前自动获取最新记录的tach_out值并赋值给当前记录的tach_in:
from jam import models from sqlalchemy import func, desc class Flight(models.Model): tach_in = models.IntegerField() tach_out = models.IntegerField() flight_duration = models.IntegerField() flight_total = models.IntegerField() @classmethod def before_insert(cls, record): # 按主键倒序获取最新的一条飞行记录 last_flight = cls.query.order_by(desc(cls.id)).first() if last_flight: record.tach_in = last_flight.tach_out # 第一条记录可设置初始值(按需调整) else: record.tach_in = 0
此后创建新条目时,tach_in会自动填充为上一条的tach_out,仅需手动输入新的tach_out。
问题b:自动计算累计总飞行时间flight_total
在同一个before_insert钩子中补充累计计算逻辑,先算出当前记录的飞行时长,再累加历史总时长得到flight_total:
@classmethod def before_insert(cls, record): # 先执行问题a的填充逻辑 last_flight = cls.query.order_by(desc(cls.id)).first() if last_flight: record.tach_in = last_flight.tach_out else: record.tach_in = 0 # 自动计算当前飞行时长(若未提前实现) record.flight_duration = record.tach_out - record.tach_in # 计算历史总飞行时长,加上当前时长得到累计值 total_history = cls.query.with_entities(func.sum(cls.flight_duration)).scalar() or 0 record.flight_total = total_history + record.flight_duration
补充提示
如果数据库涉及多架飞机,需在查询时添加飞机ID过滤条件(如cls.query.filter(cls.aircraft_id == record.aircraft_id)...),确保仅统计同一架飞机的记录;模型层钩子能覆盖所有创建记录的场景(包括表单、API或批量导入),比仅在表单层处理更通用。
内容的提问来源于stack exchange,提问作者Sierra Alpha
相关产品推荐
相关产品推荐

