簡體   English   中英

使用SQLAlchemy(Python)創建模型對象時生成GUID

[英]Generate GUID when creating model object using SQLAlchemy (Python)

我正在將postgres與SQLAlchemy一起使用。 我想創建Profile對象,並讓它們自動生成GUID。 但是目前我的個人資料ID不存儲任何值,例如:

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

我研究了其他人如何在其模型中實現GUID( 如何在SQLAlchemy中使用UUID? ),我知道許多人不建議使用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列中生成默認值。

任何幫助,將不勝感激!

您的代碼是正確的!

提交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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM