【问题标题】:sqlalchemy auto incrementing column based on other columnssqlalchemy 基于其他列的自动递增列
【发布时间】:2020-10-08 17:02:10
【问题描述】:

是否可以在同一个表中拥有基于多个列的自动递增列。 例如,在下表中,我有两列(item_id 和 col)决定列计数器中的数字。为特定 item_id 添加到 col 的每个新值都会将特定 item_idcounter 列下的数字增加一。 所以 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


    【解决方案1】:

    您的计数器没有增加;您检索了 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-11
      • 1970-01-01
      • 2018-04-17
      • 2014-09-09
      • 1970-01-01
      • 2023-01-08
      • 1970-01-01
      • 2011-10-13
      相关资源
      最近更新 更多