【发布时间】:2020-10-08 17:02:10
【问题描述】:
是否可以在同一个表中拥有基于多个列的自动递增列。
例如,在下表中,我有两列(item_id 和 col)决定列计数器中的数字。为特定 item_id 添加到 col 的每个新值都会将特定 item_id 的 counter 列下的数字增加一。
所以 counter 完全依赖于 item_id 和 col。
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)
【问题讨论】:
标签: python sqlalchemy