ENUM type in SQLAlchemy with PostgreSQL

前端 未结 4 1992
我寻月下人不归
我寻月下人不归 2020-12-24 07:48

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 documentatio

4条回答
  •  借酒劲吻你
    2020-12-24 08:37

    The code below worked for me on SQLAlchemy 1.3.11 and Postgres 12.0.

    You must first create the Enum type in postgres before creating the user table. This can be done directly through sql statement.

    CREATE TYPE permission AS ENUM ('READ_ONLY', 'READ_WRITE', 'ADMIN', 'OWNER');
    

    Then set up the project model

    from flask_sqlalchemy import SQLAlchemy    
    
    db = SQLAlchemy()
    
    class User(db.Model): 
        __tablename__ = 'user'
    
        user_id = db.Column(db.Integer, primary_key=True)   
        username = db.Column(db.String(120), unique=True, nullable=False)
        password = db.Column(db.String(200), nullable=False)
        access = db.Column(db.Enum('READ_ONLY', 'READ_WRITE', 'ADMIN', 'OWNER', name="permission"))
    

提交回复
热议问题