使用现有对象(FastAPI)初始化新对象的Pydantic初始化对象

发布于 2025-02-13 04:02:31 字数 678 浏览 0 评论 0原文

我有一个基类,以从前端获取值。 USER_ID应来自依赖关系(deps.get_current_user)函数。

现在如何使用commentbase的值初始化新类评论库?

,这是常见的用途吗?

我得到了它与解决方法 。

​user_id = current_user.id)

class CommentBase(BaseModel, extra=Extra.allow):
    blog_id: int
    message: str


class CommentCreate(CommentBase):
    user_id: int
@router.post("/post/comment")
def post_comment_reply(
    message: schemas.CommentBase,
    current_user: models.User = Depends(deps.get_current_active_user),
    db: Session = Depends(deps.get_db),
):
    setattr(message, "user_id", current_user.id)
    print(message)

I have a Base class, to get the values from the frontend. The user_id should comes from the Depends(deps.get_current_user) function.

How can i initialize the new class CommentCreate now, with the values from CommentBase?

And is this the common use?

I got it worked with the workaround extra=Extra.allow and setattr(message,...)

I think it should be something like: commentCreate = schemas.CommentCreate(**comment, user_id=current_user.id)

class CommentBase(BaseModel, extra=Extra.allow):
    blog_id: int
    message: str


class CommentCreate(CommentBase):
    user_id: int
@router.post("/post/comment")
def post_comment_reply(
    message: schemas.CommentBase,
    current_user: models.User = Depends(deps.get_current_active_user),
    db: Session = Depends(deps.get_db),
):
    setattr(message, "user_id", current_user.id)
    print(message)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

挽清梦 2025-02-20 04:02:31

您可以使用 dict 这。

类似:

commentcreate(user_id = current_user,** message.dict())

You can use the dict method to achieve this.

something like :

CommentCreate(user_id=current_user , **message.dict())

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文