本文介绍了设置SQLAlchemy自动增量起始值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SQLAlchemy中的autoincrement参数似乎只有TrueFalse,但是我想设置下一个插入操作时通过自动递增aid = 1002的预定义值aid = 1001./p>

在SQL中,可以像这样更改:

ALTER TABLE article AUTO_INCREMENT = 1001;

我正在使用MySQL,并且我尝试了以下操作,但不起作用:

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Article(Base):
    __tablename__ = 'article'
    aid = Column(INTEGER(unsigned=True, zerofill=True),
                autoincrement=1001, primary_key=True)

那么,我该怎么办呢?预先感谢!

解决方案

您可以通过使用 DDLEvents .这将允许您在CREATE TABLE运行之后立即运行其他SQL语句.查看链接中的示例,但我想您的代码将类似于以下内容:

from sqlalchemy import event
from sqlalchemy import DDL
event.listen(
    Article.__table__,
    "after_create",
    DDL("ALTER TABLE %(table)s AUTO_INCREMENT = 1001;")
)

The autoincrement argument in SQLAlchemy seems to be only True and False, but I want to set the pre-defined value aid = 1001, the via autoincrement aid = 1002 when the next insert is done.

In SQL, can be changed like:

ALTER TABLE article AUTO_INCREMENT = 1001;

I'm using MySQL and I have tried following, but it doesn't work:

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Article(Base):
    __tablename__ = 'article'
    aid = Column(INTEGER(unsigned=True, zerofill=True),
                autoincrement=1001, primary_key=True)

So, how can I get that? Thanks in advance!

解决方案

You can achieve this by using DDLEvents. This will allow you to run additional SQL statements just after the CREATE TABLE ran. Look at the examples in the link, but I am guessing your code will look similar to below:

from sqlalchemy import event
from sqlalchemy import DDL
event.listen(
    Article.__table__,
    "after_create",
    DDL("ALTER TABLE %(table)s AUTO_INCREMENT = 1001;")
)

这篇关于设置SQLAlchemy自动增量起始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 04:39