我正在使用postgres和SQLAlchemy。我希望创建概要文件对象,并让它们自动生成GUID。但是,当前我的配置文件ID不存储任何值,例如:
profile = Profile(name='some_profile')
-> print(profile.name)
some_profile
-> print(profile.id)
None我了解了其他人是如何在他们的模型(How can I use UUIDs in SQLAlchemy?)中实现GUID的--我知道很多人不建议使用GUID作为I,但我想知道尽管如此,我还是出了问题。
下面是我当前的实现:
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列中生成默认值。
任何帮助都将不胜感激!
发布于 2018-09-30 05:35:38
你的代码是正确的!
提交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-8ec02a53cfc8https://stackoverflow.com/questions/52572679
复制相似问题