设置 SQLAlchemy 自动增量起始值 [英] Setting SQLAlchemy autoincrement start value

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

问题描述

SQLAlchemy中的autoincrement参数好像只有TrueFalse,但是我想设置预定义的值aid = 1001,下一次插入完成时通过自动增量aid = 1002.

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.

在 SQL 中,可以更改为:

In SQL, can be changed like:

ALTER TABLE article AUTO_INCREMENT = 1001;

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

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!

推荐答案

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

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 自动增量起始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆