我创建此代码是为了在sql server上创建一个具有identity的列,但此列不是主键。
我需要将name作为主键,将id作为标识列,但不是主键。问题是我不知道如何使用sqlalchemy。我试图将auto_increment设置为"id“,但它不起作用。
def change_pk(table, sql_table_name, list_pk_column):
str_pk_column = ""
for item in list_pk_column:
str_pk_column += item + ","
str_pk_column = str_pk_column[:-1]
event.listen(
table,
"after_create",
DDL(
"""ALTER TABLE {0} DROP CONSTRAINT {0}_id;
ALTER TABLE {0} ADD CONSTRAINT {0}_un_id UNIQUE (id);
ALTER TABLE {0} ADD CONSTRAINT {0}_pk PRIMARY KEY ({1})""".format(
sql_table_name, str_pk_column
)
),
)
msg_users = sa.Table(
"Msg_Users",
metadata,
sa.Column("id", sa.Integer, info={}),
sa.Column("name", sa.Unicode(50), nullable=False, info={}),
sa.Column("mobile", sa.Unicode(15), info={}),
sa.Column("email", sa.Unicode(80), info={}),
sa.Column(
"last_update",
sa.DateTime,
server_default=sa.func.current_timestamp(),
server_onupdate=sa.func.current_timestamp(),
info={},
),
sa.PrimaryKeyConstraint("id", name="Msg_Users_id"),
info={},
autoload=aload,
)
change_pk(msg_users, "Msg_Users", ["name"])有没有更简单的方法?
发布于 2019-05-14 05:19:57
您可以创建自己的用户定义类型来实现这一点。
class IdentityType(types.UserDefinedType):
def get_col_spec(self):
return 'INT Identity(1,1)'
def bind_processor(self, dialect):
def process(value):
if value is not None:
if isinstance(value, int):
return value
else:
return int(value)
else:
return None
return process
def result_processor(self, dialect, coltype):
def process(value):
if value is not None:
int(value)
return value
return process发布于 2015-09-11 17:19:07
在查看方言代码并检查documentation之后,这似乎是不可能的。
您可以尝试这样做:
from sqlalchemy import Table, Integer, Sequence, Column, Unicode
Table('test', metadata,
Column('id', Integer, Sequence('some_sequence')),
Column('name', Unicode(80), primary_key=True)).create(some_engine)但从文档上看,它应该不会起作用:
SQL Server使用IDENTITY结构提供所谓的“自动递增”行为,IDENTITY结构可以放在整数主键上。SQLAlchemy将IDENTITY视为默认的“自动增量”行为,如Column.autoincrement所述;这意味着默认情况下,表中的第一个整数主键列将被视为identity列,并将按如下方式生成DDL:
http://docs.sqlalchemy.org/en/rel_1_0/dialects/mssql.html#auto-increment-behavior
https://stackoverflow.com/questions/32434017
复制相似问题