【问题标题】:How to use Enum with schema in SQLAlchemy?如何在 SQLAlchemy 中使用 Enum 和模式?
【发布时间】:2021-03-08 15:29:53
【问题描述】:

我正在尝试使用 SQLAlchemy 在架构内创建一个表。它有一个枚举类型的列。以下是代码

import enum
import sqlalchemy
from sqlalchemy import Column, Text, Enum
from sqlalchemy.schema import CreateSchema
import sqlalchemy_utils
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class T(enum.Enum):
    X = 1
    Y = 2

ET = Enum(T, inherit_schema=True)
#ET = Enum(T, schema="schema1") # This works

class A(Base):
    __tablename__ = 'a'

    c1 = Column(Text, primary_key=True, nullable=False)
    c2 = Column(Text, nullable=False)
    c3 = Column(ET)

engine = sqlalchemy.create_engine("postgresql://postgres:mypass@172.17.0.2/mydb")

engine.execute(CreateSchema('schema1'))

schema_engine = engine.execution_options(schema_translate_map = { None: "schema1" } )
Base.metadata.create_all(schema_engine)

这在“create_all”行失败并出现以下错误

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.DuplicateObject) 类型“t”已经存在 [SQL:“CREATE TYPE schema1.t AS ENUM ('X', 'Y')"](此错误的背景:http://sqlalche.me/e/f405

我使用这种模式是因为我将有多个模式,必须在其中创建同一个表。

【问题讨论】:

    标签: sqlalchemy


    【解决方案1】:

    您收到错误的原因是因为您使用的版本中有bug

    我建议使用虚拟环境并使用 SQLAlchemy 的最新稳定版本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-07
      • 2019-06-01
      • 2014-11-12
      • 1970-01-01
      • 2018-09-22
      • 2018-09-02
      • 1970-01-01
      • 2016-12-24
      相关资源
      最近更新 更多