ENUM type in SQLAlchemy with PostgreSQL

前端 未结 4 1988
我寻月下人不归
我寻月下人不归 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:38

    @Tim's answer is definitely correct but I wanted to offer the way I setup my ENUMs.

    In my models.py I will create the values as tuples

    skill_levels = ('Zero', 'A little', 'Some', 'A lot')

    Then I will create a skill_level_enum variable and assign it an ENUM class with the skill level values as args.

    skill_level_enum = ENUM(*skill_levels, name="skill_level")

    In my table model then I pass in the skill_level_enum

    class User(db.Model):
        id = db.Column(db.Integer(), primary_key=True)
        skill_level = db.Column(skill_level_enum)
    

    I have found this makes my code a lot cleaner and I'm able to make updates to the skill_levels at the top of my file rather than scanning my models for the right thing to update.

提交回复
热议问题