当我尝试为给定表定义唯一性约束和索引时,我在SQL Alchemy中遇到一个奇怪的错误。
from sqlalchemy.sql import func
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, BigInteger, \
String, Numeric, DateTime, Boolean
from sqlalchemy.dialects.postgresql import ARRAY
from sqlalchemy.schema import Index, UniqueConstraint
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import sqlalchemy
Base = declarative_base()
class CommonColumns(object):
id = Column(Integer,
primary_key=True,
autoincrement=True
)
created_at = Column(
DateTime,
server_default=func.now()
)
updated_at = Column(
DateTime,
server_default=func.now(),
server_onupdate=func.now()
)
class Example(CommonColumns, Base):
__tablename__ = 'encoding'
model_name = Column(String)
model_version = Column(String)
product_id = Column(BigInteger)
position = Column(Integer)
file_name = Column(String)
image_type = Column(String)
encoding = Column(ARRAY(Numeric))
sku = Column(String)
__table_args__ = (
UniqueConstraint(
model_name,
model_version,
product_id,
position,
file_name,
image_type,
name='example_unique'
),
Index(
model_name,
model_version,
product_id,
position,
file_name,
image_type,
name='example_index'
),
{}
)
connection_string = sqlalchemy.engine.url.URL(
drivername='<removed>',
username='<removed>',
password='<removed>',
database='<removed>',
host='<removed>'
)
engine = create_engine(connection_string)
Session = sessionmaker(bind=engine)
session = Session()
Base.metadata.create_all(engine)
session.commit()
此代码导致以下错误:
回溯(最近通话最近): 文件“ /Users/ryan.zotti/Documents/repos/recommendations/name_example.py”,第30行,在 类Example(CommonColumns,Base): 在示例中,文件“ /Users/ryan.zotti/Documents/repos/recommendations/name_example.py”,第60行 名称='encoding_index' TypeError: init ()为参数“ name”获得了多个值
为什么会发生名称冲突?我分别为name
和UniqueConstraint
定义Index
。
我正在使用SQLAlchemy==1.3.8
和Postgres 9.5。
答案 0 :(得分:0)
冲突发生在model_name
和name="example_index"
之间。 Index
__init__
方法的第一个参数是名称,因此请尝试以下操作:
Index(
"example_index",
model_name,
model_version,
product_id,
position,
file_name,
image_type
)
发件人:https://docs.sqlalchemy.org/en/13/core/constraints.html#sqlalchemy.schema.Index