【问题标题】:Generate GUID when creating model object using SQLAlchemy (Python)使用 SQLAlchemy (Python) 创建模型对象时生成 GUID
【发布时间】:2019-03-05 11:24:31
【问题描述】:

我正在使用带有 SQLAlchemy 的 postgres。我想创建 Profile 对象并让它们自动生成 GUID。但是目前我的个人资料 ID 不存储任何值,例如:

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

我研究了其他人如何在他们的模型中实现 GUID (How can I use UUIDs in SQLAlchemy?) 我知道很多人不建议将 GUID 用作 ID,但我想知道我哪里出了问题。

这是我当前的实现:

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)

我仍然是 python 的初学者,但据我了解,我将我的 Profile id 列的类型声明为 GUID(由 GUID 类设置)。因此,通过 uuid.uuid4() 在该列中生成默认 GUID 值时应成功存储。

我的猜测是 GUID 类没有任何问题,而是我尝试在 id 列中生成默认值的方式。

任何帮助将不胜感激!

【问题讨论】:

    标签: python postgresql sqlalchemy uuid guid


    【解决方案1】:

    你的代码是正确的!

    提交profile后,就可以得到有效的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
    

    【讨论】:

    • 是的,行得通!谢谢!不知道我怎么没有意识到:)
    猜你喜欢
    • 2013-11-07
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多