gpt4 book ai didi

python - 无法呈现 类型的元素

转载 作者:行者123 更新时间:2023-11-29 12:32:50 27 4
gpt4 key购买 nike

我从 Flask-common 看到了这段代码在第 57 行:

id = db.Column(UUID, default=lambda: str(uuid.uuid4()), primary_key=True)

所以我想尝试一下并在我的应用程序的 models.py 中使用它(因为我更喜欢为我的 ID 使用 uuid 类型)

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy.dialects.postgresql import UUID
import uuid

from app import db

class CostCenter(db.Model):
__tablename__ = "costcenter"

id = db.Column('id', UUID(as_uuid=True), default=lambda: str(uuid.uuid4()), primary_key=True)
name = db.Column('name', db.Text)

def __init__(self, name):
self.name = name

def __repr__(self):
return '<id {}>'.format(self.id)

但是当我尝试运行 python manage.py db upgrade 时,它会导致错误:

  File "build/bdist.linux-x86_64/egg/sqlalchemy/sql/compiler.py", line 190, in __init__                                                          
File "build/bdist.linux-x86_64/egg/sqlalchemy/sql/compiler.py", line 213, in process
File "build/bdist.linux-x86_64/egg/sqlalchemy/sql/visitors.py", line 81, in _compiler_dispatch
File "build/bdist.linux-x86_64/egg/sqlalchemy/sql/compiler.py", line 2164, in visit_create_table
File "build/bdist.linux-x86_64/egg/sqlalchemy/util/compat.py", line 199, in raise_from_cause
File "build/bdist.linux-x86_64/egg/sqlalchemy/sql/compiler.py", line 2153, in visit_create_table
File "build/bdist.linux-x86_64/egg/sqlalchemy/sql/compiler.py", line 213, in process
File "build/bdist.linux-x86_64/egg/sqlalchemy/sql/visitors.py", line 81, in _compiler_dispatch
File "build/bdist.linux-x86_64/egg/sqlalchemy/sql/compiler.py", line 2184, in visit_create_column
File "build/bdist.linux-x86_64/egg/sqlalchemy/dialects/sqlite/base.py", line 847, in get_column_specification
File "build/bdist.linux-x86_64/egg/sqlalchemy/sql/compiler.py", line 261, in process
File "build/bdist.linux-x86_64/egg/sqlalchemy/sql/visitors.py", line 79, in _compiler_dispatch
sqlalchemy.exc.CompileError: (in table 'costcenter', column 'id'): Compiler <sqlalchemy.dialects.sqlite.base.SQLiteTypeCompiler object at 0x7fc16
c1f1a50> can't render element of type <class 'sqlalchemy.dialects.postgresql.base.UUID'>

为什么它不能呈现 UUID 类型?它在SQLAlchemy 中可以识别,但为什么在Flask-SQLAlchemy 中不能识别?

最佳答案

您的列定义使用了一个仅适用于 postgresql 的函数,并且您的数据库类型是 sqlite。

你需要这个:

id = db.Column(
'id',
db.Text(length=36),
default=lambda: str(uuid.uuid4()),
primary_key=True)

关于python - 无法呈现 <class 'sqlalchemy.dialects.postgresql.base.UUID' > 类型的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36806403/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com