LoopingDev
LoopingDev

Reputation: 844

flask sqlalchemy doesn't update rows

I'm using Flask-SQLAlchemy with postgresql locally hosted and I've this code where I'm supposed to update the user's data in the database once he login

    user_id = current_user.get_id()
    print(f"\n\n user_id: {user_id}\n\n") #1--->
    x = users.query.filter_by(id=user_id).first()
    x.sid = request.sid
    db.session.commit()
    print(f'\n\n user_object.sid:{x.sid} , request.sid:{request.sid}  \n\n') #2 --->

#1 : userid:1

#2 : x.sid:QKfGvdsL-HGUM-FHHYF, request.sid:QKfGvdsL-HGUM-FHHYF

but then when I look at pgadmin4 or request the value of x.sid later it's always "null"

I looked everywhere and everyone seems to suggest the same way I wrote my code with.

Worth mentioning :

  1. sid column has been added using flask.migrate, it hasn't been created with the table.
  2. Just to make sure that there is nothing in my code the overwrites the value afterwords, pgadmin4 to overwrite the null to something unique and it stayed, nothing happened to its value.
  3. i tried to use db.session.add(x) but it kept saying that data info already exists

Upvotes: 1

Views: 913

Answers (1)

richardkovacs
richardkovacs

Reputation: 154

You could try:

db.session.merge(x)
db.session.commit()

This code creates a new row, if it did not exist, else updates the existing one.

Upvotes: 7

Related Questions