I'm making a small and simple API, to do some CRUD operations. And I have never used an ORM before.
I have two tables with the exact same schema, one for active state and one for historic events.
I came up with this hacky way of inserting the records to the historic tables:
crud.py
def update_active(db: Session, active: schemas.Active):
if active.case_1:
active.status = "Case 1"
elif active.case_2:
active.status = "Case 2"
elif active.case_3:
active.status = "Case 3"
else:
active.case_4= "Case 0"
active.timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
if not active.case_end:
active.case_end = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
if active.status == "Case 0":
history = db.query(models.Active).filter(
models.Active.node_id == active.node_id and
models.Active.frequency == active.frequency and
models.Active.status != active.status
).all()
for result in history:
copy_res = result.__dict__.copy()
copy_res.pop('_sa_instance_state')
query = insert(models.History).values(**copy_res)
db.execute(query)
db.query(models.Active).filter(
models.Active.node_id == active.node_id and
models.Active.frequency == active.frequency
).update(active)
db.commit()
return active
I don't like this part:
for result in history:
copy_res = result.__dict__.copy()
copy_res.pop('_sa_instance_state')
query = insert(models.History).values(**copy_res)
db.execute(query)
Is there a better way to insert these into the historic table?