I can't use computed and pydantic_model_creator properly. #1947
-
I just wanted to add followers_count and followings_count to response when calling model_dump() or model_dump_json().# users_app/test.py ProfilePydantic = pydantic_model_creator(cls=UserModel)
@users_router.get(path="/test-user-response-model")
async def test_user_response_model():
try:
model: Optional[UserModel] = await UserModel.get_or_none(
username="atajanov_kamronbek",
password="@kamronbek2003",
).prefetch_related("followers", "followings")
pydantic_model = await ProfilePydantic.from_tortoise_orm(obj=model)
print(f"pydantic_model.model_dump_json: {pydantic_model.model_dump()}")
return pydantic_model.model_dump_json()
except Exception as e:
my_logger.error(f"Exception e: {e}")
raise HTTPException(status_code=400, detail=f"Internal Server Error e: {e}") # users_app/models.py
# console error log
|
Beta Was this translation helpful? Give feedback.
Answered by
waketzheng
May 22, 2025
Replies: 1 comment
-
For compute field, you have to explicit init model before create the pydantic model class: There are several examples for pydantic. |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
KAMRON-DEVELOPER
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For compute field, you have to explicit init model before create the pydantic model class:
tortoise-orm/examples/pydantic/tutorial_4.py
Line 81 in 503c93b
There are several examples for pydantic.
And welcome to make PR if you have new example to share.