SQLAlchemy update if unique key exists

后端 未结 2 494
盖世英雄少女心
盖世英雄少女心 2020-12-28 16:01

I\'ve got a class:

class Tag(Base, TimestampMixin):
    \"\"\"Tags\"\"\"
    __tablename__ = \'tags\'
    __table_args__ = {\'mysql_engine\' : \'InnoDB\', \'         


        
2条回答
  •  有刺的猬
    2020-12-28 16:49

    You can try this

    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
    

    You can check the link https://stackoverflow.com/search?q=Insert+on+duplicate+update+sqlalchemy

提交回复
热议问题