postgresql 在使用SQLAlchemy和Mapped创建表时指定timestamp列类型提示

dphi5xsq  于 2023-11-18  发布在  PostgreSQL
关注(0)|答案(2)|浏览(206)

我为表定义了Post类,但是我得到了以下错误。如何在我现有的类中包含时间戳,以便使postgres为每个条目注册时间戳?
main.py

from fastapi import FastAPI, Response, status, HTTPException, Depends
from fastapi.params import Body  # for storing user sending data
from typing import Optional
from pydantic import BaseModel
from random import randrange
import psycopg2
import time
from . import model
from .database import engine, Session, get_db

model.Base.metadata.create_all(bind=engine)

from psycopg2.extras import RealDictCursor

import os

app = FastAPI()

@app.get("/sqlalchemy")
def test_posts(db: Session = Depends(get_db)):
    return {"status": "success"}

# module.py
from .database import Base
from sqlalchemy.orm import Mapped
from sqlalchemy.orm import mapped_column

# from sqlalchemy.sql.sqltypes import TIMESTAMP
from sqlalchemy.sql.expression import text
from sqlalchemy.types import TIMESTAMP

class Post(Base):
    __tablename__ = "posts"
    id: Mapped[int] = mapped_column(primary_key=True, nullable=False)
    title: Mapped[str] = mapped_column(nullable=False)
    content: Mapped[str] = mapped_column(nullable=False)
    published: Mapped[bool] = mapped_column(server_default="true", nullable=False)
    created_at: Mapped[TIMESTAMP(timezone=True)] = mapped_column(
        nullable=False, server_default=text("now()")
)

字符串
错误代码:

File "/home/shri/Desktop/projects/.venv/lib/python3.10/site-packages/sqlalchemy/orm/properties.py", line 791, in _init_column_for_annotation
    new_sqltype = registry._resolve_type(check_type)
  File "/home/shri/Desktop/projects/.venv/lib/python3.10/site-packages/sqlalchemy/orm/decl_api.py", line 1268, in _resolve_type
    search = ((pt, pt) for pt in python_type_type.__mro__)
AttributeError: 'TIMESTAMP' object has no attribute '__mro__'


我想知道如何正确定义;

created_at: Mapped[TIMESTAMP(timezone=True)] = mapped_column(
    nullable=False, server_default=text("now()")
)


为它的自动时间登记制作posgres

ocebsuys

ocebsuys1#

Mapped中的类型必须是 *Python类型 *,而不是SQLAlchemy类型。这个声明应该可以工作:

from datetime import datetime

created_at: Mapped[datetime] = mapped_column(
    TIMESTAMP(timezone=True), server_default=sa.text('now()')
)

字符串
(note你不需要提供 nullable,因为它暗示了Map类型是否是可选的)。
另请参阅2.0中的新输入项。

cu6pst1q

cu6pst1q2#

使用SQLAlchemy2.0 DeclarativeBase/mapped语法,func导入用于指定timestam.now()字段值。
此SQLAlchemy页提供示例代码。https://docs.sqlalchemy.org/en/20/changelog/whatsnew_20.html
以下示例使用[Optional]类型Map将'created_at'字段设置为可空。使用SQLAlchemy -> sqlite测试。

from typing import Optional  
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column  
from sqlalchemy.sql import func  
from datetime import datetime  

class Base(DeclarativeBase):  
    pass

class Book(Base):  
    __tablename__ = "book"  
      
    id: Mapped[int] = mapped_column(primary_key=True)
    title: Mapped[str] = mapped_column(String(100))
    author: Mapped[str] = mapped_column(String(100))
    review: Mapped[str] = mapped_column(String(200))
    optional_1: Mapped[Optional[str]] = mapped_column(String(100), default='A default value here')
    created_at: Mapped[Optional[datetime]] = mapped_column(default=func.now())

字符串

相关问题