How to increase a counter in SQLAlchemy

后端 未结 3 1188
后悔当初
后悔当初 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:26

    If you are using the SQL layer, then you can use arbitrary SQL expressions in the update statement:

    conn.execute(tags.update(tags.c.tag_id == 5).values(count=tags.c.count + 1))
    

    The ORM Query object also has an update method:

    session.query(Tag).filter_by(tag_id=5).update({'count': Tag.count + 1})
    

    The ORM version is smart enough to also update the count attribute on the object itself if it's in the session.

提交回复
热议问题