将记录输入Postgres时出现验证错误

2024-10-03 23:20:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用以下查询创建了一个表

CREATE TABLE user_account (
user_id serial PRIMARY KEY,
user_name VARCHAR ( 50 ) UNIQUE NOT NULL,
password VARCHAR ( 50 ) NOT NULL,
email VARCHAR ( 255 ) UNIQUE NOT NULL,
created_on TIMESTAMP NOT NULL,
allow BOOLEAN NOT NULL
);

下面是我的models.py

class AccountsInfo(Base):
    __tablename__ = "user_account"

    user_id = Column(Integer, primary_key=True, index=True)
    user_name = Column(String)
    password = Column(String)
    email = Column(String)
    created_on = Column(DateTime)
    allow = Column(Boolean)

下面是我的schema.py

class AccountsInfoBase(BaseModel):
    user_name: str
    password: str
    email: str
    created_on: str
    allow: bool

    class Config:
        orm_mode = True


class AccountsCreate(AccountsInfoBase):
    password = str


class AccountsInfo(AccountsInfoBase):
    user_id: int

    class Config:
        orm_mode = True

我使用以下代码创建一个用户

def create_user(db: Session, user: schemas.AccountsCreate):
    db_user = models.AccountsInfo(user_name=user.user_name, password=user.password, email=user.email,created_on=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())),allow=True)
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user

问题是我得到了以下错误

raise ValidationError(errors, field.type_) pydantic.error_wrappers.ValidationError: 1 validation error for AccountsInfo response -> created_on str type expected (type=type_error.str)

我错过了什么


Tags: nametruedbonemailnotcolumnpassword
1条回答
网友
1楼 · 发布于 2024-10-03 23:20:44

raise ValidationError(errors, field.type_) pydantic.error_wrappers.ValidationError: 1 validation error for AccountsInfo response -> created_on str type expected (type=type_error.str)

在您的表中,创建的时间是DateTime

class AccountsInfo(Base):
    __tablename__ = "user_account"

    created_on = Column(DateTime)

但是您在Pydantic模型中声明为str

class AccountsInfoBase(BaseModel):
    created_on: str

将字段声明为datetime in Pydantic模型。SQLAlchemy还提供了自动创建日期时间的功能

from sqlalchemy.sql import func

time_created = Column(DateTime(timezone=True), server_default=func.now())

相关问题 更多 >