2

I'm using postgres with SQLAlchemy. I want to create Profile objects and have them autogenerate a GUID. However currently my profile IDs don't store any values, e.g:

profile = Profile(name='some_profile')
-> print(profile.name)
some_profile
-> print(profile.id)
None

I've looked into how others are implementing GUIDs into their models (How can I use UUIDs in SQLAlchemy?) I understand that many people don't recommend using GUIDs as IDs, but I would like to know where I'm going wrong despite this.

Here's my current implementation:

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String
from sqlalchemy.types import TypeDecorator, CHAR
import uuid

Base = declarative_base()

class GUID(TypeDecorator):
    """Platform-independent GUID type.

    Uses Postgresql's UUID type, otherwise uses
    CHAR(32), storing as stringified hex values.

    """
    impl = CHAR

    def process_bind_param(self, value, dialect):
        if value is None:
            return value
        elif dialect.name == 'postgresql':
            return str(value)
        else:
            if not isinstance(value, uuid.UUID):
                return "%.32x" % uuid.UUID(value).int
            else:
                # hexstring
                return "%.32x" % value.int

    def process_result_value(self, value, dialect):
        if value is None:
            return value
        else:
            if not isinstance(value, uuid.UUID):
                value = uuid.UUID(value)
            return value



class Profile(Base):
    __tablename__ = 'profile'

    id = Column(GUID(), primary_key=True, default=uuid.uuid4)
    name = Column(String)

I'm still a beginner to python, but as far as I understand I'm declaring the type of my Profile id column as a GUID (setup by the GUID class). A default GUID value should therefore be successfully stored when generated in that column through uuid.uuid4().

My guess is that there isn't anything wrong with the GUID class, but instead in how I'm trying to generate the default value within the id column.

Any help would be appreciated!

solarflare
  • 880
  • 2
  • 8
  • 23

1 Answers1

0

Your code is correct!

After you commit the profile, you can get the valid id.

profile = Profile(name='some_profile')
-> print(profile.name)
some_profile
-> print(profile.id)
None

# commit
session.add(profile)
session.commit()

# print saved profile
-> print(profile.name)
some_profile
-> print(profile.id)
ff36e5ff-16b5-4536-bc86-8ec02a53cfc8
Feng
  • 559
  • 3
  • 8