AttributeError: 'UUID' object has no attribute 'replace' when using backend-agnostic GUID type

The Oracle picture The Oracle · Nov 22, 2017 · Viewed 24k times · Source

I want to have a primary key id with type uuid in a Postgresql database using SQLAlchemy 1.1.5, connecting to the database with the pg8000 adapter. I used the Backend-agnostic GUID Type recipe from the SQLAlchemy documentation.

When I want to insert into the database, I get the following error

  File ".../guid.py", line ???, in process_result_value
    return uuid.UUID(value)
  File "/usr/lib/python2.7/uuid.py", line 131, in __init__
    hex = hex.replace('urn:', '').replace('uuid:', '')
AttributeError: 'UUID' object has no attribute 'replace'

my model looks like this

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
from guid import GUID
import uuid

base = declarative_base()

class Item(base):
    __tablename__ = 'item'

    id = Column(GUID(), default=uuid.uuid4, nullable=False, unique=True, primary_key=True)
    name = Column(String)
    description = Column(String)

    def __repr__(self):
        return "<Item(name='%s', description='%s')>" % (self.name, self.description)

My resource or controller looks like this

data = req.params
item = Item(name=data['name'], description=data['description'])

self.session.add(item)
self.session.commit()

Answer

jrc picture jrc · Oct 27, 2018

This should fix it:

id = Column(GUID(as_uuid=True), ...)

from https://bitbucket.org/zzzeek/sqlalchemy/issues/3323/in-099-uuid-columns-are-broken-with:

"If you want to pass a UUID() object, the as_uuid flag must be set to True."