T
T
Tibor1282019-11-04 08:28:07
Flask
Tibor128, 2019-11-04 08:28:07

How to update custom fields of the Sessions model in Flask?

Good afternoon!
I'm trying to learn Flask. Out of the box, the documentation is intelligible and understandable, but I needed to store in the database in the sessions table, in addition to the regular data for flask_sessions, several of my own fields.
Here is the model I created:

class Sessions(db.Model):
  __table_args__ = { 'extend_existing': True }

  user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable = True)
  room_id = db.Column(db.Integer, db.ForeignKey('room.id'), nullable = True)

Now I need to update the user_id.
In theory, I need to know the id of the record in the database.
I can't figure out how to get to it.
I tried to get to id like this:
print(app.session_interface.sql_session_model.id)
but the output is:
Sessions.id
In general, I expected it to look something like:
session.user_id = 1
session.commit()

But apparently not everything is so simple (
Actually, the question is:
How to correctly change the user_id field for the current session in the database?
UPD:
I found a solution, but it seems to me that there should be something more correct than this:
row = db.session.query(Sessions).filter_by(session_id = 'session:%s'%session.sid).first()
row.user_id = 1
db.session.commit()

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question