Skip to content

[BUG] Model fails to serialize when BackLink has been fetched #1189

@alexdlukens

Description

@alexdlukens

Hello all,

Describe the bug
When a model with a BackLink has been retrieved (with fetch_links=1, nesting_depth=1), calling model_dump or model_dump_json raises a PydanticSerializationError

To Reproduce

from beanie import init_beanie, Document, BackLink, Link
from motor.motor_asyncio import AsyncIOMotorClient
from pydantic import Field

class User(Document):
    name: str
    login: Link["Login"]

class Login(Document):
    username: str
    password: str
    user: BackLink[User] = Field(json_schema_extra={"original_field": "login"})
    
User.model_rebuild()

client = AsyncIOMotorClient("mongodb://localhost:27017")
db = client.get_database("test_db")


await init_beanie(
    db,
    document_models=[User, Login],
)

login = Login(username="alice123", password="securepassword")
await login.save()
user1 = User(name="Alice", login=login)
await user1.save()

login_doc = await Login.get(login.id, fetch_links=True, nesting_depth=1)
login_doc.model_dump_json() # error is raised here

Expected behavior

No exception should be thrown. Serialization should succeed, with or without the backlinked data

Additional context

This was the issue I attempted to solve in #1171, but my resolution was not approved. Just looking for any solution to fix the serialization issue

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions