SQLAlchemy update if unique key exists

后端 未结 2 495
盖世英雄少女心
盖世英雄少女心 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:39

    From version 1.2 SQLAlchemy will support on_duplicate_key_update for MySQL

    There is also examples of how to use it:

    from sqlalchemy.dialects.mysql import insert
    
    insert_stmt = insert(my_table).values(
        id='some_existing_id',
        data='inserted value')
    
    on_duplicate_key_stmt = insert_stmt.on_duplicate_key_update(
        data=insert_stmt.values.data,
        status='U'
    )
    
    conn.execute(on_duplicate_key_stmt)
    

    From version 1.1 SQLAlchemy support on_conflict_do_update for PostgreSQL

    Examples:

    from sqlalchemy.dialects.postgresql import insert
    
    insert_stmt = insert(my_table).values(
        id='some_existing_id',
        data='inserted value')
    
    do_update_stmt = insert_stmt.on_conflict_do_update(
        constraint='pk_my_table',
        set_=dict(data='updated value')
    )
    
    conn.execute(do_update_stmt)
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题