英文:
What is the difference between basemodel and pydantic_model_creator?
问题
I can provide the translated content as requested:
我是FastAPI的初学者,我有一个关于返回API函数内容的问题。
我知道BaseModel可以规范API函数的输入参数;我在FastAPI中使用了Tortoise ORM,并使用了"pydantic_model_creator"函数来序列化返回的API函数内容。
但是,最近我看到了另一种BaseModel的用法;它被用来定义API函数的返回内容。
例如,一个关于用户模型的函数:
base.py:
class UserInfo(BaseModel):
id: int
user_name: str
age: Optional[int]
user_type: bool
nickname: Optional[str]
user_phone: Optional[str]
user_email: Optional[str]
full_name: Optional[str]
user_status: bool
header_img: Optional[str]
sex: int
serializer.py:
single_user = pydantic_model_creator(User, name="single_user", exclude=("password", "remarks", "client_host", "create_time", "update_time",))
function.py:
async def user_info(req: Request):
"""
获取当前用户信息
user_id: int
"""
user_data = await User.get_or_none(pk=req.state.user_id)
if not user_data:
return fail(msg=f"ID {req.state.user_id} 不存在!")
print(user_data.__dict__)
# 返回成功消息及用户信息
return await single_user.from_tortoise_orm(user_data)
因此,我想要建议。这两种用法哪一种更好?
英文:
i'm a beginner in fastapi; i have a question about returning the contents of api functions.
i have knew that BaseModel could regulate the input parameters of Api functions; i used the tortoise orm in fastapi and i used "pydantic_model_creator" function to serializer returning the contents of api functions.
but,recnetly i saw another use of basemodel; it was used to define the returning contents of api functions.
example: a function about use model;
base.py:
class UserInfo(BaseModel):
id : int
user_name: str
age: Optional[int]
user_type: bool
nickname: Optional[str]
user_phone: Optional[str]
user_email: Optional[str]
full_name: Optional[str]
user_status: bool
header_img: Optional[str]
sex: int
serializer.py:
single_user = pydantic_model_creator(User, name="single_user", exclude=("password", "remarks", "client_host", "create_time", "update_time",))
fuunction.py:
async def user_info(req: Request):
"""
get current user info
user_id: int
"""
user_data = await User.get_or_none(pk=req.state.user_id)
if not user_data:
return fail(msg=f"ID{req.state.user_id} is fail!")
print(user_data.__dict__)
# return success(msg="user info", data=UserInfo(**user_data.__dict__))
return await single_user.from_tortoise_orm(user_data)
So, I want a suggestion. Which of the two uses is better?
答案1
得分: 2
以下是已经翻译好的部分:
什么是BaseModel?
Pydantic BaseModel
是一个定义数据外观和必须满足的验证要求的类。
有关更多信息,请参阅https://docs.pydantic.dev/latest/
pydantic_model_creator
的用途是什么?
pydantic_model_creator
是库tortoise-orm
中的一个函数。它是该库的一部分,因此被设计用于与它一起使用。其目标是将声明的ORM
模型转换为与其他Web框架一起使用的pydantic
模型(例如,也可以在Django中使用pydantic模型)。
整体情况:如何使用它们?
您可以使用tortoise-orm
作为ORM
,然后单独声明所有单个的pydantic
模型。这将导致需要重复的工作,并增加项目不同组件之间的耦合。因此,建议使用pydantic_model_creator
创建API
将使用并提供给ORM
的输入模型(反之亦然,因为您将检索数据并将其返回给用户)。
唯一情况下使用BaseModel
而不是pydantic_model_creator
是如果您需要返回一组特定字段或以特定方式构造的数据。不过,这应该是一个例外/罕见情况,而不是规范。
另一方面,如果您不使用tortoise-orm
,则需要自己编写模型(BaseModel
)或使用ORM
提供的工具。
英文:
There is no winner in your question. The two serve two different purposes.
What is a BaseModel?
A Pydantic BaseModel
is a class that defines how your data looks like and the validation requirements it needs to pass in order to be valid.
For further information see https://docs.pydantic.dev/latest/
What's the use of pydantic_model_creator
?
pydantic_model_creator
is a function from the library tortoise-orm
. It is part of this library and thus thought for being used with it. The goal is to transform the declared ORM
model into a pydantic
model that works with other web frameworks (e.g. pydantic models can be used also with django).
The big picture: how to use them?
You can use tortoise-orm
as ORM
and then declare separately all the single pydantic
models. This will duplicate the effort required and increase the coupling between the different components of your project. It is thus advisable to use pydantic_model_creator
to create the input models that your API
will consume and feed them to the ORM
(the converse also applies since you'll retrieve data and return it to the user).
The only case in which it would make sense to use BaseModel
instead of pydantic_model_creator
is if you need to return a particular set of fields or data structured in a particular way. Though, this should be an exception/rare case and not the norm.
On the other hand, if you're not using tortoise-orm
, you'll need to write the models (BaseModel
) yourself or use the tools provided by the ORM
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论