How can I use UUIDs in SQLAlchemy?

后端 未结 8 968
心在旅途
心在旅途 2020-12-07 10:58

Is there a way to define a column (primary key) as a UUID in SQLAlchemy if using PostgreSQL (Postgres)?

相关标签:
8条回答
  • 2020-12-07 11:41

    In case anyone is interested, I've been using Tom Willis answer, but found useful to add a string to uuid.UUID conversion in the process_bind_param method

    class UUID(types.TypeDecorator):
        impl = types.LargeBinary
    
        def __init__(self):
            self.impl.length = 16
            types.TypeDecorator.__init__(self, length=self.impl.length)
    
        def process_bind_param(self, value, dialect=None):
            if value and isinstance(value, uuid.UUID):
                return value.bytes
            elif value and isinstance(value, basestring):
                return uuid.UUID(value).bytes
            elif value:
                raise ValueError('value %s is not a valid uuid.UUId' % value)
            else:
                return None
    
        def process_result_value(self, value, dialect=None):
            if value:
                return uuid.UUID(bytes=value)
            else:
                return None
    
        def is_mutable(self):
            return False
    
    0 讨论(0)
  • 2020-12-07 11:54

    I've used the UUIDType from the SQLAlchemy-Utils package: http://sqlalchemy-utils.readthedocs.org/en/latest/data_types.html#module-sqlalchemy_utils.types.uuid

    0 讨论(0)
提交回复
热议问题