【问题标题】:Validation error while inputting a record into Postgres将记录输入 Postgres 时出现验证错误
【发布时间】:2021-05-18 17:58:24
【问题描述】:

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

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

问题是我收到以下错误,

引发 ValidationError(errors, field.type_) pydantic.error_wrappers.ValidationError: 1 验证错误 AccountsInfo 响应 -> created_on str 类型预期 (type=type_error.str)

我错过了什么?

【问题讨论】:

    标签: python sqlalchemy fastapi pydantic


    【解决方案1】:

    raise ValidationError(errors, field.type_) pydantic.error_wrappers.ValidationError: AccountsInfo 响应的 1 个验证错误 -> created_on str type expected (type=type_error.str)

    在你的表中 created_on 是 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())
    

    【讨论】:

      猜你喜欢
      • 2016-10-18
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 2016-04-16
      相关资源
      最近更新 更多