Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sqlalchemy - Updating row with a filter produces List Index Error

I hope this is my last question pertaining to this pet project of mine.

I'm trying to update table Clocktimes (column = time_out) with the current time. I want to select by a UUID that I create with UUID4. When I run the code, I get ListIndex out of range error, on a function in query.py (a part of Sqlalchemy). I've listed that rather short function below my code.

My code:

out = session.query(). \
        filter(Clocktime.p_uuid == p_uuid). \
        update(Clocktime.time_out == datetime.datetime.now())
    session.add(out)
    session.commit()

Sqlalchemy code throwing error:

def _entity_zero(self):
    return self._entities[0]

The Sqlalchemy code is pretty complex so I haven't looked through it yet, but my theory is that it doesn't like my filter for some reason. Anyway, I can't figure it out - do any of you have any idea?

like image 716
Ross Wardrup Avatar asked Apr 22 '15 22:04

Ross Wardrup


1 Answers

I do not think that your code is doing what you want it to do. There are two ways to make an update you want:

1) Directly on the database:

upd = (session.query(Clocktime)
       .filter(Clocktime.p_uuid == p_uuid)
       .update({"time_out": datetime.datetime.now()})
       )
print("# of updated rows = {}".format(upd))
# session.commit()

2) Load object(s), update the value, and commit the session

upd = (session.query(Clocktime)
       .filter(Clocktime.p_uuid == p_uuid)
       )

# assuming there should be exactly one object for given p_uuid    
clockTime = upd.one()
clockTime.time_out = datetime.datetime.now()
session.commit()
like image 174
van Avatar answered Oct 01 '22 02:10

van