首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用SQLAlchemy (Python)创建模型对象时生成GUID

使用SQLAlchemy (Python)创建模型对象时生成GUID
EN

Stack Overflow用户
提问于 2018-09-29 21:24:38
回答 1查看 3.1K关注 0票数 2

我正在使用postgres和SQLAlchemy。我希望创建概要文件对象,并让它们自动生成GUID。但是,当前我的配置文件ID不存储任何值,例如:

代码语言:javascript
复制
profile = Profile(name='some_profile')
-> print(profile.name)
some_profile
-> print(profile.id)
None

我了解了其他人是如何在他们的模型(How can I use UUIDs in SQLAlchemy?)中实现GUID的--我知道很多人不建议使用GUID作为I,但我想知道尽管如此,我还是出了问题。

下面是我当前的实现:

代码语言:javascript
复制
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的初学者,但据我所知,我将我的配置文件id列的类型声明为GUID (由GUID类设置)。因此,当通过uuid.uuid4()在该列中生成时,应该成功地存储默认GUID值。

我的猜测是GUID类没有什么问题,而是我如何在id列中生成默认值。

任何帮助都将不胜感激!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-09-30 05:35:38

你的代码是正确的!

提交profile之后,可以获得有效的id

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52572679

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档