Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set default value using SqlAlchemy_Utils ChoiceType

I just migrated from NoSQL to SQL, and I'm rather new to the SqlAlchemy ORM.

In my use case, I need a field in models to be able to store a given choice set:

# models.py
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.utils.types.choice import ChoiceType

Base = declarative_base()    

class User(Base):
    __tablename__ = 'user'
    USER_TYPES = [
       ('user', 'User'),
       ('admin', 'Admin User')
    ]

    id = Column(Integer(), primary_key=True)
    type = Column(ChoiceType(User_Types), default='user')

But when I run my script, I get:

> SAWarning: Unicode column 'None' has non-unicode default value 'user' specified.
  self.default

And no errors on other fields where I set default values and type not "ChoiceType").

Anyone knows what I did wrong?

Thanks!

like image 514
benjaminz Avatar asked Oct 15 '15 16:10

benjaminz


1 Answers

ChoiceType column is Unicode(255) by default. The Unicode type is a String subclass that assumes input and output as Python unicode data. You should set default as unicode string

type = Column(ChoiceType(USER_TYPES), default=u'user')

Or you can set impl parameter

type = Column(ChoiceType(USER_TYPES, impl=String()), default='user')
like image 67
r-m-n Avatar answered Sep 30 '22 07:09

r-m-n