python - sqlalchemy 基于其他列的自动递增列
问题描述
是否可以在同一个表中拥有基于多个列的自动递增列。例如,在下表中,我有两列(item_id 和 col)来决定列计数器中的数字。col
为特定添加的每个新值都会将该特定列item_id
下的数字增加一。所以计数器完全依赖于 item_id 和 col。counter
item_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)
解决方案
你的计数器没有增加;您检索了 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)
推荐阅读
- visual-studio-2019 - visual studio 2019 找不到团队
- javascript - 如何在重定向之前触发 GTM 代码?
- postgresql - 为什么我在 postgres 上复制功能时出现美元报价错误
- r - 从特定月份开始按年份分组数据
- grep - 预先匹配号码以输出grep的匹配行?
- .net - NLog MappedDiagnosticsLogicalContext.SetScoped 用于多个键
- python - Dropbox 中的文件夹名称
- jsf - 我不能使用 varStatus 值来获取 p:repeat 中的索引
- spring-integration - 发布订阅频道可能存在问题
- ansible - 使用角色启动 ansible playbook 时出错