I saw this snippet of code from Flask-common at line 57:
id = db.Column(UUID, default=lambda: str(uuid.uuid4()), primary_key=True)
So I thought I give it a try and use it in my app's models.py
(because I prefer to have uuid
type for my id's)
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)
But when I try to run python manage.py db upgrade
, it results to an error:
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'>
Why can't it render the type UUID? It is recognized in SQLAlchemy
but how come it can't in Flask-SQLAlchemy
?
Your column definition is using a function that only works with postgresql, and your database type is sqlite.
You need this:
id = db.Column('id', db.Text(length=36), default=lambda: str(uuid.uuid4()), primary_key=True)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With