SQLAlchemy更新(如果存在唯一密钥)
我有一堂课:
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
课堂上保持这种逻辑似乎更加明确-可能使我无法进行the弹枪手术。
我如何到达那里?我对Python
和非常陌生SQLAlchemy
,因此,对我的代码有任何其他想法将不胜感激。
谢谢。
PSSQLAlchemy
是如此巨大,他们没有提供方便的方法,对INSERT ... ON DUPLICATE KEY UPDATE
吧?哇!
-
你可以试试这个
def get_or_increase_tag(tag_name): tag = session.query(Tag).filter_by(tag=tag_name).first() if not tag: tag = Tag(tag_name) else: tag.cnt += 1 return tag
您可以检查链接https://stackoverflow.com/search?q=Insert+on+duplicate+update+sqlalchemy