首页 > 解决方案 > sqlalchemy 基于其他列的自动递增列

问题描述

是否可以在同一个表中拥有基于多个列的自动递增列。例如,在下表中,我有两列(item_id 和 col)来决定列计数器中的数字。col为特定添加的每个新值都会将该特定列item_id下的数字增加一。所以计数器完全依赖于 item_id 和 col。counteritem_id

id   |  item_id  |      counter    |       col          |
  0  |   1       |       1         |       value1       |
  1  |   1       |       2         |       value2       |
  2  |   1       |       3         |       value3       |
  3  |   2       |       1         |       value4       |
  4  |   2       |       2         |       value5       |
  5  |   3       |       1         |       value6       |
  6  |   3       |       2         |       value7       |
  7  |   3       |       3         |       value8       | 
  8  |   1       |       4         |       value9       |

这是我尝试过的:

from sqlalchemy.event import listen
from sqlalchemy.sql.functions import func
from sqlalchemy import Column, Integer, UniqueConstraint
from sqlalchemy.orm import sessionmaker
engine = create_engine('sqlite:///:memory:', echo=True) #TEST DB
Base = declarative_base()
Session = sessionmaker(bind=engine)
session = Session()
class User(Base):
    __tablename__ = 'invoice'
    id = Column(Integer, primary_key=True)
    item_id= Column(Integer)
    col = Column(String)
    counter = Column(Integer)

    __table_args__ = (UniqueConstraint(item_id, counter),)

    @staticmethod
    def increment(mapper, connection, user):
        last = session.query(func.max(User.counter).label('last')).filter(User.item_id== user.item_id).first()
        user.last = last.last if last else 1

listen(User, "before_insert", User.increment)

标签: pythonsqlalchemy

解决方案


你的计数器没有增加;您检索了 max() 但没有添加一个。这对我有用:

    @staticmethod
    def increment(mapper, connection, user):
        last = (
            session.query(func.max(User.counter))
            .filter(User.item_id == user.item_id)
            .scalar()
        )
        user.counter = 1 + (last if last else 0)

推荐阅读