python - 具有枚举列类型的 Sqlalchemy 模型
问题描述
我正在尝试将我的 python 枚举存储在一个表中。我尝试关注 stackoverflow 帖子,但现在出现此错误:
File "c:\users\arrchana\pycharmprojects\be\venv\lib\site-packages\sqlalchemy\dialects\postgresql\base.py", line 2231, in format_type
raise exc.CompileError("PostgreSQL ENUM type requires a name.")
sqlalchemy.exc.CompileError: PostgreSQL ENUM type requires a name.
这是我的代码:
from appInits.db import db
from enums.goalTypes import GoalTypes
from sqlalchemy import types
class EnumAsInteger(types.TypeDecorator):
"""Column type for storing Python enums in a database INTEGER column.
This will behave erratically if a database value does not correspond to
a known enum value.
"""
impl = types.Integer # underlying database type
def __init__(self, enum_type):
super(EnumAsInteger, self).__init__()
self.enum_type = enum_type
def process_bind_param(self, value, dialect):
if isinstance(value, self.enum_type):
return value.value
raise ValueError('expected %s value, got %s'
% (self.enum_type.__name__, value.__class__.__name__))
def process_result_value(self, value, dialect):
return self.enum_type(value)
def copy(self, **kwargs):
return EnumAsInteger(self.enum_type)
class Tasks(db.Model):
__tablename__ = 'tasks'
id = db.Column(db.Integer, primary_key=True, unique=True)
text = db.Column(db.Text, unique=True, nullable=False)
difficulty = db.Column(db.Integer, unique=False, nullable=False)
tool = db.Column(EnumAsInteger(GoalTypes), nullable=False)
def __repr__(self):
return '<Task {}: {}, {}, {}>'.format(self.id, self.difficulty, self.tool, self.text)
def __init__(self, id, text, difficulty, tool):
self.id = id
self.text = text
self.difficulty = difficulty
self.tool = tool
解决方案
推荐阅读
- java - 为什么我的 SensorEventListener 实现不起作用?未收到 onSensorChanged 回调
- reactjs - 从 redux-saga reactJS 中的 api 获取数据
- sql - 将一列拆分为多列(数量和名称未知)
- java - 通过提供者将 POJO 序列化为 JSON
- vba - 定义公共字典
- javascript - 我的 AddEventListener 函数在任何浏览器中都不起作用。如何解决?
- plc - PLC 和 OPC 服务器之间的连接
- powershell - Excel中的Powershell:在标题和每第二行中设置颜色
- c# - outlook.com 网络插件 | 如何在顶部功能区上显示加载项
- c++ - OpenGL点精灵uv坐标无法正常工作