BeanieODM / beanie

Asynchronous Python ODM for MongoDB
http://beanie-odm.dev/
Apache License 2.0
2.07k stars 219 forks source link

[BUG] BackLink causes error when using model_json_schema() #1008

Open gdlmx opened 2 months ago

gdlmx commented 2 months ago

Describe the bug Generating Json Schema from a document with a BackLink field will fail with the error: PydanticInvalidForJsonSchema.

To Reproduce

from typing import List
from pydantic import Field
from beanie import Document, Link, BackLink

class Task(Document):
    detail: str
    owner:  Link["User"]

class User(Document):
    name: str
    tasks: List[BackLink["Task"]] = Field(json_schema_extra={"original_field": "owner"})

User.model_json_schema()

The last line will raise error:

PydanticInvalidForJsonSchema: Cannot generate a JsonSchema for core_schema.PlainValidatorFunctionSchema ({'type': 'with-info', 'function': <function BackLink.build_validation.<locals>.validate at 0x7f89140bdd00>})

Expected behavior The last line (model_json_schema) should return

{
  "properties": {
    "_id": { "...":"..." },
    "name": {  "title": "Name",  "type": "string"  },
    "tasks": { "...":"..." }
  },
  "required": [ "name", "tasks" ],
  "title": "User",
  "type": "object"
}

Additional context Python version: 3.11 Beanie version: 1.26.0 Pydantic version: 2.8.2

gdlmx commented 2 months ago

Possible cause of this error:

https://github.com/BeanieODM/beanie/blob/51e73ebc297df02082c5c683d555f7d057c4f6aa/beanie/odm/fields.py#L473-L479

See this discussion of a similar error with Pydantic v2.4

A correct implementation already exists on the Link class.

https://github.com/BeanieODM/beanie/blob/bdb6a8692c87ff289c61e6b7df608e30767a94d8/beanie/odm/fields.py#L408-L430

adeelsohailahmed commented 2 months ago

Thanks for reporting the issue, and taking the time to investigate the cause. Would you like to send a PR to fix this issue, @gdlmx?

xalien10 commented 2 months ago

@adeelsohailahmed @gdlmx Any updated about this fix yet?

gdlmx commented 2 months ago

Thanks for reporting the issue, and taking the time to investigate the cause. Would you like to send a PR to fix this issue, @gdlmx?

Yes, I can prepare a PR to fix it. Could you provide me some idea about the proper json schema for BackLink?

Given this line

https://github.com/BeanieODM/beanie/blob/51e73ebc297df02082c5c683d555f7d057c4f6aa/beanie/odm/fields.py#L468

There is no guarantee of any field in a BackLink object, is there?

adeelsohailahmed commented 2 months ago

There is no guarantee of any field in a BackLink object, is there?

I'm not sure if I fully understand your question here. Could you elaborate more?

xalien10 commented 2 months ago

@gdlmx is there any update about the PR? :-)