使用SQLAlchemy的Postgres中的枚举数组 [英] Array of Enum in Postgres with SQLAlchemy
问题描述
在过去的一年中,我一直在成功地使用一系列带有postgres和SQLAlchemy的枚举,例如:
I've been using an array of enums with postgres and SQLAlchemy successfully over the past year like so:
class MyModel(BaseModel):
enum_field = Column(postgresql.ARRAY(EnumField(MyEnum, native_enum=False)))
EnumField
来自 sqlalchemy_enum34 库,这是一个内置的枚举的小包装,它使用Python枚举而不是字符串来表示Python枚举。
The EnumField
is from the sqlalchemy_enum34 library, a small wrapper around the builtin enum that uses Python enums as Python representation instead of strings.
尽管文档说,不支持枚举数组,我想它起作用了,因为我选择'native_enum = False'。
最近我注意到它不再起作用了,我认为这是由于从SQLA 1.0升级到1.1引起的,但是我不确定。
Although the docs say, array of enum is not supported, I guess it worked, because I chose 'native_enum=False'. Recently I noticed that it doesn't work anymore, I think it's due to the upgrade from SQLA 1.0 to 1.1, but I'm not sure.
问题在于,它会生成无效的DQL:
The problem is, that it generates invalid DQL:
CREATE TABLE my_model (
enum_field VARCHAR(5)[3] NOT NULL CHECK (contexts IN ('ONE', 'TWO', 'THREE'))
)
我得到的错误是:
ERROR: malformed array literal: "ONE"
DETAIL: Array value must start with "{" or dimension information.
有什么办法可以找回枚举数组吗?
:当它起作用时,实际上没有创建任何CHECK约束,只是一个可变数组。只要我可以在我的Python代码中使用枚举(例如 query.filter(enum_field == MyEnum.ONE)
)
Any idea how I can get back my enum array?
By the way: when it worked, no CHECK constraint was actually created, just an array of varying. I'm ok with that as long as I can use enums in my Python code (e.g. query.filter(enum_field==MyEnum.ONE)
)
推荐答案
您可能想添加create_constraint = False,看看是否可行
you probably want to add create_constraint=False, see if that works
我现在可以创建表(无需任何检查)。
I can now create the table (without any CHECK).
这篇关于使用SQLAlchemy的Postgres中的枚举数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!