Examples to clarify an important issue in accepted responses to comments
I did not understand this until I played with it myself, so I thought that there would be others who would be baffled. Let's say you are working with a user whose id == 6 and whose no_of_logins == 30 at startup.
# 1 (bad) user.no_of_logins += 1
Essence
By referring to a class instead of an instance, you can make SQLAlchemy be smarter with respect to the increment, so that this happens on the database side rather than on the Python side. Doing this in the database is better because it is less vulnerable to data corruption (for example, two clients try to grow at the same time with the net result of only one increment instead of two). I assume that you can increment in Python if you set locks or increase isolation, but why bother if you don't need it?
Warning
If you are going to increase twice using the code that generates SQL, for example, SET no_of_logins = no_of_logins + 1 , then you will need to commit or at least reset between increments, otherwise you will get only one increase:
# 6 (bad) user.no_of_logins = User.no_of_logins + 1 user.no_of_logins = User.no_of_logins + 1 session.commit()
MarredCheese Sep 01 '19 at 7:19 2019-09-01 01:19
source share