使用SQLAlchemy的Postgres中的枚举数组

编程入门 行业动态 更新时间:2024-10-25 20:28:06
本文介绍了使用SQLAlchemy的Postgres中的枚举数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在过去的一年中,我一直在成功地使用一系列带有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))

推荐答案

迈克·拜耳在 sqlalchemy邮件列表:

您可能想添加create_constraint = False,看看是否可行

you probably want to add create_constraint=False, see if that works

docs.sqlalchemy/en/latest/core/type_basics.html? Highlight = enum#sqlalchemy.types.Enum.params.create_constraint

我现在可以创建表(无需任何检查)。

I can now create the table (without any CHECK).

更多推荐

使用SQLAlchemy的Postgres中的枚举数组

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

发布评论

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

>www.elefans.com

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