How to increase a counter in SQLAlchemy

后端 未结 3 1186
后悔当初
后悔当初 2020-12-04 21:55

Suppose I have table tags which has a field count that indicates how many items have been tagged with the given tag.

How do I

3条回答
  •  悲哀的现实
    2020-12-04 22:34

    If you have something like:

    mytable = Table('mytable', db.metadata,
        Column('id', db.Integer, primary_key=True),
        Column('counter', db.Integer)
    )
    

    You can increment fields like this:

    m = mytable.query.first()
    m.counter = mytable.c.counter + 1
    

    Or, if you have some mapped Models, you can write alternatively:

    m = Model.query.first()
    m.counter = Model.counter + 1
    

    Both versions will return the sql statement you have asked for. But if you don't include the column and just write m.counter += 1, then the new value would be calculated in Python (and race conditions are likely to happen). So always include a column as shown in the two examples above in such counter queries.

提交回复
热议问题