我有一堂课:
class Tag(Base, TimestampMixin):
"""Tags"""
__tablename__ = 'tags'
__table_args__ = {'mysql_engine' : 'InnoDB', 'mysql_charset' : 'utf8' }
id = Column(Integer(11), autoincrement = True, primary_key = True)
tag = Column(String(32), nullable = False, unique = True)
cnt = Column(Integer(11), index = True, nullable = False, default = 1)
def __init__(self, tag):
t = session.query(Tag).filter_by(tag=tag).first()
if t:
self.cnt = t.cnt+1
self.tag = t.tag
else:
self.tag = tag
def __repr__(self):
return "<Tag('%s')>" % (self.tag, )
def __unicode__(self):
return "%s" % (self.tag, )
添加标签时:
tag = Tag('tag')
session.add(tag)
session.commit()
我希望它更新现有的 tag
。
当然,我可以这样做:
tag = session.query(Tag).filter_by(tag='tag').first()
if tag:
tag.cnt++
else:
tag = Tag('tag')
session.add(tag)
session.commit()
但是,将这种逻辑保留在 Tag
类中似乎更加清晰 - 可能让我远离霰弹枪手术。
我如何到达那里?我是 Python
和 SQLAlchemy
的新手,所以对我的代码有任何额外的想法将不胜感激。
原文由 Nemoden 发布,翻译遵循 CC BY-SA 4.0 许可协议
你可以试试这个
您可以查看链接 https://stackoverflow.com/search?q=Insert+on+duplicate+update+sqlalchemy