tortoise-orm: Unable to use computed values from relations after Pydantic v2 upgrade
Describe the bug
I’m unable to use computed values from relations since upgraded to Pydantic v2. When using the class method from_tortoise_orm the following error are occurring
File "/some-path/projects/debug-tortoise-orm/.venv/lib/python3.11/site-packages/pydantic/main.py", line 353, in model_dump_json
return self.__pydantic_serializer__.to_json(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
pydantic_core._pydantic_core.PydanticSerializationError: Error serializing to JSON: AttributeError: '__main__.Employee.leaf' object has no attribute 'team_members'
To Reproduce [CODE UPDATED] The following snippet shows how to reproduce.
from tortoise import Tortoise, fields, run_async
from tortoise.contrib.pydantic import pydantic_model_creator
from tortoise.exceptions import NoValuesFetched
from tortoise.models import Model
class Employee(Model):
name = fields.CharField(max_length=50)
manager: fields.ForeignKeyNullableRelation["Employee"] = fields.ForeignKeyField(
"models.Employee", related_name="team_members", null=True
)
team_members: fields.ReverseRelation["Employee"]
talks_to: fields.ManyToManyRelation["Employee"] = fields.ManyToManyField(
"models.Employee", related_name="gets_talked_to"
)
gets_talked_to: fields.ManyToManyRelation["Employee"]
def name_length(self) -> int:
return len(self.name)
def team_size(self) -> int:
try:
return len(self.team_members)
except NoValuesFetched:
return -1
class PydanticMeta:
computed = ["name_length", "team_size"]
allow_cycles = True
max_recursion = 4
async def run():
await Tortoise.init(db_url="sqlite://:memory:", modules={"models": ["__main__"]})
await Tortoise.generate_schemas()
Employee_Pydantic = pydantic_model_creator(Employee)
root = await Employee.create(name="Root")
loose = await Employee.create(name="Loose")
_1 = await Employee.create(name="1. First H1", manager=root)
_2 = await Employee.create(name="2. Second H1", manager=root)
await _1.talks_to.add(_2, root, loose)
await _2.gets_talked_to.add(_1, loose)
# The error ocurs here, after calling `from_tortoise_orm`
p = await Employee_Pydantic.from_tortoise_orm(await Employee.get(name="Root"))
print(p.model_dump_json(indent=4))
if __name__ == "__main__":
run_async(run())
Expected behavior Pydantic serializes the model.
About this issue
- Original URL
- State: open
- Created 3 years ago
- Reactions: 1
- Comments: 16 (12 by maintainers)
Since this issue has not yet been solved. I propose a temporary solution. Based on the solution from @waketzheng
monkey_patch.py
base_model.py
@janusheide Seems that it is not a bug, just use
getattrinstead of .attrThe following code snippet worked at my machine (MacOS+Python3.11+tortoise-orm0.20.1)