带有 PostgreSQL 的 SQLAlchemy 中的 ENUM 类型 [英] ENUM type in SQLAlchemy with PostgreSQL

查看:49
本文介绍了带有 PostgreSQL 的 SQLAlchemy 中的 ENUM 类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 SQLAlchemy core 与 postgresql 数据库一起使用,我想将 ENUM 类型添加到我的表定义中.根据 postgresql 文档,必须事先定义 ENUM 类型到正在创建的表:

I'm using SQLAlchemy core with a postgresql database and I would like to add the ENUM type to my table definition. According to the postgresql documentation, the ENUM type must be defined prior to the table being created:

CREATE TYPE gender_enum AS ENUM ('female', 'male');

CREATE TABLE person (
  name VARCHAR(20),
  gender gender_enum
);

问题是我在创建表定义时.在阅读了 SQLAlchemy 文档 后,我可以找不到任何实现示例.我试过这样的事情,但没有奏效:

The problem is when I'm creating the table definition. After reading the SQLAlchemy documentation I couldn't find any implementation examples. I've tried something like this but it didn't work:

from sqlalchemy.dialects.postgresql import ENUM

person = Table('user_profile', metadata,
    Column('name', String(20)),
    Column('gender', ENUM('female', 'male'))
);

必须怎么做?

推荐答案

需要从 sqlalchemy 中导入 Enum 并为其添加名称.它应该像这样工作:

You need to import Enum from sqlalchemy and add a name to it. It should work like this:

from sqlalchemy import Enum

person = Table("user_profile", metadata,
    Column("name", String(20)),
    Column("gender", Enum("female", "male", name="gender_enum", create_type=False))
);

这篇关于带有 PostgreSQL 的 SQLAlchemy 中的 ENUM 类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆