我在第57行看到了来自Flask-common的这段代码:
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
中怎么没有?
答案 0 :(得分:3)
您的列定义使用的函数仅适用于postgresql,而您的数据库类型是sqlite。
你需要这个:
id = db.Column('id', db.Text(length=36), default=lambda: str(uuid.uuid4()), primary_key=True)
答案 1 :(得分:0)
如果使用 postgresql 数据库,您可以使用UUID
。