首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >datetime的ValidationError

datetime的ValidationError
EN

Stack Overflow用户
提问于 2021-10-07 16:40:12
回答 1查看 149关注 0票数 0

嗨,谢谢你阅读这篇长篇文章。我正在学习FastAPI-SQLAlchemy-PostgresSQL。我将按照本教程编写一个演示项目。我的数据库是这样创建的:

代码语言:javascript
复制
CREATE TABLE posts (
    id SERIAL PRIMARY KEY,
    title text,
    content text,
    owner_id integer REFERENCES users(id),
    date_created timestamp without time zone,
    date_last_updated timestamp without time zone
);

-- Indices -------------------------------------------------------

CREATE UNIQUE INDEX posts_pkey ON posts(id int4_ops);

我的SQLAlchemy模型如下所示:

代码语言:javascript
复制
class Post(Base):
    __tablename__ = 'posts'

    id = Column(Integer, primary_key=True, index=True)
    title = Column(String, index=True)
    content = Column(String, index=True)
    owner_id = Column(Integer, ForeignKey('users.id'))
    date_created = Column(DateTime, default=dt.datetime.now)
    date_last_updated = Column(DateTime, default=dt.datetime.now)

    owner = relationship("User", back_populates="posts")

Pydantic Schema看起来像这样:

代码语言:javascript
复制
class PostBase(BaseModel):
    title: str
    content: str


class PostCreate(PostBase):
    pass


class Post(PostBase):
    id: int
    owner_id: int
    date_create: dt.datetime
    date_last_updated: dt.datetime

    class Config:
        orm_mode = True

最后,我用下面的代码创建了一个帖子:

代码语言:javascript
复制
def create_post(db: Session, post: schemas.PostCreate, user_id: int):
    post = models.Post(**post.dict(), owner_id=user_id)
    db.add(post)
    db.commit()
    db.refresh(post)
    return post

@app.post("/users/{user_id}/posts", response_model=schemas.Post)
def create_post(user_id: int, post: schemas.PostCreate, db: Session = Depends(get_db)):
    user = crud.get_user(user_id=user_id, db=db)
    if user is None:
        raise HTTPException(status_code=404, detail="User not found")
    return create_post(db=db, post=post, user_id=user_id)

我可以看到该帖子已在数据库中正确创建:| id | title|content|owner_id|date_created |date_last_updated || -- |-|--|-||3| hihi |3 |2021-10-08 03:00:43.731416|2021-10-08 03:00:43.73143

但是控制台会打印以下错误,并且API不会返回JSON

代码语言:javascript
复制
ERROR:    Exception in ASGI application
Traceback (most recent call last):
  File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/uvicorn/protocols/http/httptools_impl.py", line 375, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/uvicorn/middleware/proxy_headers.py", line 75, in __call__
    return await self.app(scope, receive, send)
  File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/fastapi/applications.py", line 208, in __call__
    await super().__call__(scope, receive, send)
  File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/starlette/applications.py", line 112, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/starlette/middleware/errors.py", line 181, in __call__
    raise exc from None
  File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/starlette/middleware/errors.py", line 159, in __call__
    await self.app(scope, receive, _send)
  File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/starlette/exceptions.py", line 82, in __call__
    raise exc from None
  File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/starlette/exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/starlette/routing.py", line 580, in __call__
    await route.handle(scope, receive, send)
  File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/starlette/routing.py", line 241, in handle
    await self.app(scope, receive, send)
  File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/starlette/routing.py", line 52, in app
    response = await func(request)
  File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/fastapi/routing.py", line 234, in app
    response_data = await serialize_response(
  File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/fastapi/routing.py", line 137, in serialize_response
    raise ValidationError(errors, field.type_)
pydantic.error_wrappers.ValidationError: 1 validation error for Post
response -> date_create
  field required (type=value_error.missing)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-10-07 16:47:11

代码语言:javascript
复制
pydantic.error_wrappers.ValidationError: 1 validation error for Post
response -> date_create
  field required (type=value_error.missing)

这是您的错误,您没有填写一个字段,这是表单所必需的。

检查表单中是否需要date_created

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69484851

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档