如何在 SQLAlchemy 中增加计数器 [英] How to increase a counter in SQLAlchemy
问题描述
假设我有一个 tags
表,它有一个 count
字段,表示有多少 items
用给定的标签进行了标记.
Suppose I have table tags
which has a field count
that indicates how many items
have been tagged with the given tag.
在添加带有现有标记的新项目后,如何在 SQLAlchemy 中增加此计数器?
How do I increase this counter in SQLAlchemy after I add a new item with an existing tag?
使用纯 SQL 我会执行以下操作:
With plain SQL I would do the following:
INSERT INTO `items` VALUES (...)
UPDATE `tags` SET count=count+1 WHERE tag_id=5
但是我如何在 SQLAlchemy 中表达 count=count+1
?
But how do I express count=count+1
in SQLAlchemy?
推荐答案
如果你有类似的问题:
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
两个版本都会返回你要求的sql语句.但是,如果您不包含该列而只编写 m.counter += 1
,那么新值将在 Python 中计算(并且可能会发生竞争条件).因此,请始终在此类计数器查询中包含上面两个示例中所示的列.
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.
这篇关于如何在 SQLAlchemy 中增加计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!