4

I'm using python-flask, sqlalchemy. I had a problem about sqlalchemy results. I want specific column results from my table so I tried this

query = session.query(Table.column_one, Table.coulmn_two).first()

so I had results, but I can't update that results. I tried like this

query.column_one = value

or

setattr(query, column_one, value)

but the results is:

AttributeError: can't set attribute

so I found this post Can't set attribute on result objects in SQLAlchemy flask and in this post, there is no way to set attribute from that query. Is this real? Is there no way?

2
  • How did you print the result?
    – arshovon
    Oct 3, 2018 at 5:05
  • i just print (query), so the result is like that : (column_one, column_two)
    – KimJangHun
    Oct 3, 2018 at 5:52

1 Answer 1

9

There are many methods!

Method #1:

You have to get the whole object to update it

Try this:

query = session.query(Table).first()
query.column_one = value # setattr(query, column_one, value)
session.commit()

Method #2:

Using SQLAlchemy Core API

from sqlalchemy import update

stmt = update(Table).where(Table.c.id==5).values(id=1)

More information about this method on this link

There are other methods, mentioned by Ilja Everilä in the comments , So the credit goes to him, upvote his comment!

Method #3:

load_only() method, It can get used like this:

from sqlalchemy.orm import load_only

query = session.query(Table).options(load_only("column_one", "column_two"))
query.column_one = Value
session.commit()

More information about load_only() method on this link

Method #4:

Query.update()

session.query(Table).filter(Table.column_one == 25).update({Table.column_one: 10}, synchronize_session=False)
session.commit()

More information about Query.update() here!

8
  • thanks answer but i had a performance issue. The whole query like query(table) is too slow(because my table has lots of column...) so i just want to modify some specific column
    – KimJangHun
    Oct 3, 2018 at 6:40
  • I'll update the answer, there is a Core API that let u update without selecting and loading the whole object
    – DarkSuniuM
    Oct 3, 2018 at 6:46
  • @KimJangHun Updated.
    – DarkSuniuM
    Oct 3, 2018 at 6:52
  • 1
    Just as a side note: load_only() is also an option, if trying to avoid loading wide tables. There's also Query.update(), if one wants to use the session instead of Core. Oct 3, 2018 at 7:22
  • 2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.