使用PostgreSQL的SQLAlchemy中的ENUM类型 [英] ENUM type in SQLAlchemy with PostgreSQL

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

问题描述

我正在使用一个postgresql数据库的 SQLAlchemy core ,我想将 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 the table is 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 example. 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 a 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天全站免登陆