我已经使用SQLALChemy2.0‘S MappdAsDataclass和DeclarativeBase模型创建了一些表,创建的表如下:


class Base(MappedAsDataclass, DeclarativeBase):
    """subclasses will be converted to dataclasses"""

class Post(Base):
    __tablename__ = 'allposts'
    post_id: Mapped[int] = mapped_column(init=False, primary_key=True)
    collection_id: Mapped[int] = mapped_column(ForeignKey("collections.collection_id"), default=None, nullable=True)
    user: Mapped[str] = mapped_column(default=None, nullable=True)
    title: Mapped[str] = mapped_column(default=None, nullable=True)
    description: Mapped[str] = mapped_column(default=None, nullable=True)
    date_added: Mapped[datetime.datetime] = mapped_column(default=None, nullable=True)
    date_modified: Mapped[Optional[datetime.datetime]] = mapped_column(default=None, nullable=True)
    tags: Mapped[list]  = mapped_column(ARRAY(TEXT, dimensions=1), default=None, nullable=True)
    views: Mapped[int] = mapped_column(default=0, nullable=True)

Post.__table__

Base.metadata.create_all(engine)

我想使用GUID作为PK,但我在使用DeclarativeBase/MappdAsDataclass通过SQLALChemy创建UUID类型列时遇到了问题

我试着像这样做一个UUID专栏,但没有运气:

from sqlalchemy.dialects.postgresql import UUID

class Post(Base):
    __tablename__ = 'allposts'
    post_id: Mapped[int] = mapped_column(init=False, primary_key=True)
    guid: Mapped[uuid.uuid1] = mapped_column(default=None, nullable=True)
    collection_id: Mapped[int] = mapped_column(ForeignKey("collections.collection_id"), default=None, nullable=True)
    user: Mapped[str] = mapped_column(default=None, nullable=True)
    title: Mapped[str] = mapped_column(default=None, nullable=True)
    description: Mapped[str] = mapped_column(default=None, nullable=True)
    date_added: Mapped[datetime.datetime] = mapped_column(default=None, nullable=True)
    date_modified: Mapped[Optional[datetime.datetime]] = mapped_column(default=None, nullable=True)
    tags: Mapped[list]  = mapped_column(ARRAY(TEXT, dimensions=1), default=None, nullable=True)
    views: Mapped[int] = mapped_column(default=0, nullable=True)

我try 了uuid.uuid1的不同版本,但如果这是问题所在,我猜错了.

some SQLAlchemy examples of UUID columns here个,但我似乎想不出如何将其转化为我正在使用的模型.

推荐答案

以下是如何在PostgreSQL服务器上执行此操作的示例:

import uuid

from sqlalchemy import create_engine, select, text, types
from sqlalchemy.orm import (DeclarativeBase, Mapped, MappedAsDataclass,
                            mapped_column, sessionmaker)

DATABASE_URL = "postgresql+psycopg2://test_username:test_password@localhost:5432/test_db"
engine = create_engine(
    DATABASE_URL,
    echo=True,
)
Session = sessionmaker(
    bind=engine,
)


class Base(MappedAsDataclass, DeclarativeBase):
    pass


class Post(Base):
    __tablename__ = 'post'
    guid: Mapped[uuid.UUID] = mapped_column(
        types.Uuid,
        primary_key=True,
        init=False,
        server_default=text("gen_random_uuid()") # use what you have on your server
    )


if __name__ == "__main__":
    Base.metadata.create_all(engine)

    with Session() as session:
        post1 = Post()
        post2 = Post()
        session.add_all([post1, post2])
        session.commit()

    with Session() as session:
        for post in session.scalars(select(Post)):
            print(post)

在这里,它使用服务器缺省值让服务器为我们生成UUID.

CREATE TABLE post (
        guid UUID DEFAULT gen_random_uuid() NOT NULL,
        PRIMARY KEY (guid)
)

结果将是:

Post(guid=UUID('b8b01f06-8daf-4c2c-9a7b-c967c752a7bf'))
Post(guid=UUID('7b94c8a3-ff0e-4d09-92e9-caf4377370e1'))

Python相关问答推荐

重命名变量并使用载体中的字符串存储 Select 该变量

取相框中一列的第二位数字

Odoo onchange for invoice_Status of sale事件.订单未触发

如何在Pygame中绘制右对齐的文本?

如何判断LazyFrame是否为空?

如何在Python中增量更新DF

无法使用python.h文件; Python嵌入错误

在上下文管理器中更改异常类型

剧作家Python没有得到回应

具有多个选项的计数_匹配

我在使用fill_between()将最大和最小带应用到我的图表中时遇到问题

运行Python脚本时,用作命令行参数的SON文本

图像 pyramid .难以创建所需的合成图像

如何获得每个组的时间戳差异?

形状弃用警告与组合多边形和多边形如何解决

启用/禁用shiny 的自动重新加载

Plotly Dash Creating Interactive Graph下拉列表

isinstance()在使用dill.dump和dill.load后,对列表中包含的对象失败

寻找Regex模式返回与我当前函数类似的结果

Python避免mypy在相互引用中从另一个类重定义类时失败