现在 SQLAlchemy 2 具有 内置 Uuid 类型,而不是依赖自定义的 与后端无关的 GUID 类型,有没有办法将自动生成的 uuid 作为主键?
我试过这个:
import sqlalchemy as sa
import sqlalchemy.orm as so
from project import db
class User(db.Model):
id: so.Mapped[sa.Uuid] = so.mapped_column(primary_key=True)
username: so.Mapped[str] = so.mapped_column(sa.String(64), index=True, unique=True)
但我收到错误“sqlalchemy.exc.ArgumentError:'id'属性映射注释内提供的类型是 SQLAlchemy 类型
我明白错误的含义,但我不知道从哪里开始。我刚刚开始使用 SQLAlchemy。
您有两个选择,使用从 python 生成的 UUID,或者使用从数据库生成的 UUID。无论您选择哪种方法,进入
Mapped
的类型都应该是来自 python 的 UUID
,而不是来自 SQLAlchemy 的 Uuid
。以下代码显示了如何生成两者。我已经使用 PostgreSQL 及其相应的函数(gen_random_uuid()
)来生成 uuid,但是您可以使用任何数据库函数,如果您使用 MySQL,请说 uuid()
。
from uuid import uuid4, UUID
from sqlalchemy import create_engine, func
from sqlalchemy.orm import DeclarativeBase, mapped_column, Mapped, Session
class Base(DeclarativeBase):
pass
engine = create_engine("postgresql+psycopg://some_connection_string")
class UserWithPythonDefault(Base):
__tablename__ = "table_with_uuid_from_python"
id: Mapped[UUID] = mapped_column(primary_key=True, default=uuid4)
class UserWithServerDefault(Base):
__tablename__ = "table_with_uuid_from_db"
id: Mapped[UUID] = mapped_column(primary_key=True, server_default=func.gen_random_uuid())
Base.metadata.create_all(engine)
with Session(engine) as session:
obj_with_python_default = UserWithPythonDefault()
obj_with_server_default = UserWithServerDefault()
session.add(obj_with_python_default)
session.add(obj_with_server_default)
session.commit()