SQLAlchemy automatically converts str to unicode on commit

Posted by Victor Stanciu on Stack Overflow See other posts from Stack Overflow or by Victor Stanciu
Published on 2010-06-13T20:15:25Z Indexed on 2010/06/13 21:12 UTC
Read the original article Hit count: 304

Filed under:
|
|
|

Hello,

When inserting an object into a database with SQLAlchemy, all it's properties that correspond to String() columns are automatically transformed from <type 'str'> to <type 'unicode'>. Is there a way to prevent this behavior?

Here is the code:

from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData
from sqlalchemy.orm import mapper, sessionmaker

engine = create_engine('sqlite:///:memory:', echo=False)
metadata = MetaData()

table = Table('projects', metadata,
    Column('id', Integer, primary_key=True),
    Column('name', String(50))
)

class Project(object):
    def __init__(self, name):
        self.name = name

mapper(Project, table)
metadata.create_all(engine)

session = sessionmaker(bind=engine)()

project = Project("Lorem ipsum")

print(type(project.name))

session.add(project)
session.commit()

print(type(project.name))

And here is the output:

<type 'str'>
<type 'unicode'>

I know I should probably just work with unicode, but this would involve digging through some third-party code and I don't have the Python skills for that yet :)

© Stack Overflow or respective owner

Related posts about python

Related posts about beginner