使用现有对象(FastAPI)初始化新对象的Pydantic初始化对象
我有一个基类,以从前端获取值。 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 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())