[BUG]: Unable to serialize unknown type: <class 'beanie.odm.fields.BackLink'>
advayumare opened this issue · 6 comments
advayumare commented
Unable to return response model containing BackLink
Getting pydantic serialization error when tying to return model containing BackLink
I have following code
from typing import List
from fastapi import status
from beanie import Document, BackLink, Link, WriteRules
from pydantic import Field
class House(Document):
name: str
owner: Link["Person"]
class Person(Document):
name: str
house: BackLink[House] = Field(original_field="owner")
@app.post(
"/house",
response_model=House,
status_code=status.HTTP_201_CREATED,
)
async def create_house(
house: House = Body(...)
):
person = Person(name="Batman", house=house)
house.person = person
await house.save(link_rule=WriteRules.WRITE)
if house:
await house.sync()
return house
Expected behavior
After calling post api with following request body
{
"name": "Bat Cave"
}
the response should have been
{
"id": "1",
"name": "Bat Cave",
"owner": {
"name": "Batman",
"house": "1"
}
}
instead it gives me following error while serializing owner object
Unable to serialize unknown type: <class 'beanie.odm.fields.BackLink'>
travka47 commented
Somebody please help :_)
07pepa commented
@advayumare have you tried this? since your example will only work for pydantic v1
class Person(Document):
name: str
house: BackLink[House] = Field(json_schema_extra={"original_field": "owner"})
travka47 commented
@07pepa
In my example there is pydantic 2.7
class Feature(Document, FeatureSchema):
id: PydanticObjectId = Field(default_factory=PydanticObjectId, alias='_id', serialization_alias='id')
bugreports: Optional[List[BackLink[Bugreport]]] = Field(default=None,
json_schema_extra={"original_field": "feature"})
class Settings:
collection = "features"
max_nesting_depths_per_field = {
"bugreports": 1
}
class FeatureWithoutGeometry(Feature):
type: SkipJsonSchema[Optional[str]] = Field(default=None, exclude=True)
geometry: SkipJsonSchema[Optional[Geometry]] = Field(default=None, exclude=True)
class Bugreport(Document, BugreportSchema):
id: PydanticObjectId = Field(default_factory=PydanticObjectId, alias='_id', serialization_alias='id')
feature: Link["Feature"]
class Settings:
collection = 'bugreports'
max_nesting_depths_per_field = {
"feature": 2
}
features = await Feature.find(fetch_links=False).project(FeatureWithoutGeometry).to_list()
Error appears when fetch_links is False