P
P
pcdesign2015-02-27 15:52:51
Flask
pcdesign, 2015-02-27 15:52:51

How to do an update in flask sqlalchemy?

In its pure form in sql, the query looks like this: Googled on this subject, but all the solutions did not fit. The user_id entry in the stat table is not unique. Here's an example: ========================= MariaDB []> select id , date , user_id from stat where user_id = 2 limit 0,3 ; +-------+---------------------+---------+ | id | date | user_id | +-------+---------------------+---------+ | 63573 | 2011-12-18 17:20:17 | 2 | | 63653 | 2011-12-18 18:51:33 | 2 | | 63654 | 2011-12-18 18:51:39 | 2 | +-------+---------------------+---------+ 3 rows in set (0.00 sec) = ========================
update stat set user_id=1 where user_id=2




And all the solutions that are googled are designed to update only one row.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey Alekseev, 2015-02-27
@pcdesign

Through filter or filter_by you can get the desired strings - filter and filter_by . Then you can loop through all the entries and write down the desired value.
BUT! this is not the best approach, or rather it is a bad approach! SQLAlchemy has one good method - update. As a result, you can do everything like this:

u_id = get_userid()
rows = Stat.query.filter_by(user_id = u_id).update({'user_id': 1})
db.session.commit()

In general, you don’t need to google anything, everything is in the official documentation .

K
kirildzr, 2015-02-27
@kirildzr

user = User.query.get(1)
user.email = '[email protected]'
db.session.add(user)
db.session.commit()
blog.miguelgrinberg.com/post/the-flask-mega- tutori...

B
bromzh, 2015-02-27
@bromzh

You can write your own migration. If something goes wrong, roll back.
There is a plugin for the flask (which is a wrapper over alembic )

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question