【问题标题】:Query Enum column in sqlalchemy leads to LookupErrorsqlalchemy 中的查询枚举列导致 LookupError
【发布时间】:2019-04-09 05:14:30
【问题描述】:

我以为我非常密切地关注文档,使用 sqlalchemy 在 Postgres DB 中设置了一个 ENUM 字段,但我显然做错了一些事情(希望是一些简单的事情)。

我的表有一个类型contact_type

                                        List of data types
 Schema |     Name      | Internal name | Size |   Elements    |  Owner   | Access privileges | Description
--------+---------------+---------------+------+---------------+----------+-------------------+-------------
 public | contact_types | contact_types | 4    | unknown      +| postgres |                   |
        |               |               |      | incoming_text+|          |                   |
        |               |               |      | incoming_call+|          |                   |
        |               |               |      | outgoing_call |          |                   |

在表格中:

  Table "public.calls"
    Column    |           Type           |                     Modifiers
--------------+--------------------------+----------------------------------------------------
 contact_type | contact_types            |

在 python 中,我根据the docs 创建了一个enum 的子类:

import enum

class contact_types(enum.Enum):
    unknown: 1
    incoming_text: 2
    incoming_call: 3
    outgoing_call: 4

并将其传递给模型:

class Call(db.Model):
    contact_type = db.Column(db.Enum(contact_types))

一切看起来都很好。插入工作,我可以在查看表格时看到这些值,但 SQLAlchemy 的验证在查询时似乎不满意。这会导致错误:

calls = Call.query.order_by(Call.time.desc()).limit(pagesize).offset(offset)
for c in calls:
    print(c)

LookupError: "unknown" 不在定义的枚举值中

'unknown' 在枚举中。我是否错过了将查询连接到枚举类的步骤?

【问题讨论】:

    标签: python python-3.x postgresql sqlalchemy


    【解决方案1】:

    enum 定义中应该有=,而不是:

    class contact_types(enum.Enum):
        unknown = 1
        incoming_text = 2
        incoming_call = 3
        outgoing_call = 4
    

    【讨论】:

    • 哦,天哪,太多的 javascript 感染了大脑……至少这是一个简单的修复。谢谢。
    猜你喜欢
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2020-05-27
    • 1970-01-01
    • 1970-01-01
    • 2016-07-08
    • 2022-10-23
    • 2016-04-23
    相关资源
    最近更新 更多