设置SQLAlchemy自动增量起始值

编程入门 行业动态 更新时间:2024-10-11 17:25:00
本文介绍了设置SQLAlchemy自动增量起始值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

SQLAlchemy中的autoincrement参数似乎只有True和False,但是我想设置下一个插入操作时通过自动递增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自动增量起始值

本文发布于:2023-07-15 13:12:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1111414.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:增量   SQLAlchemy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!