SQLAlchemy更新(如果存在唯一密钥)

发布于 2021-01-29 15:13:40

我有一堂课:

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吧?哇!

关注者
0
被浏览
49
1 个回答
知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看