Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BUG] model_dump defaults to mode=python #1273

Open
orf opened this issue Aug 21, 2024 · 0 comments
Open

[BUG] model_dump defaults to mode=python #1273

orf opened this issue Aug 21, 2024 · 0 comments

Comments

@orf
Copy link

orf commented Aug 21, 2024

Describe the bug
All calls to BaseModel.model_dump use the default mode argument, which is python and not json. For example:

This means models that use custom types (such as any of these built-in Pydantic types) do not work:

import pydantic, ninja

api = NinjaAPI()

class SomeModel(pydantic.BaseModel):
    url: pydantic.AnyUrl

@api.get("/test")
def example(request) -> SomeModel:
    return SomeModel.model_validate({
        "url": "custom-protocol://foo/bar"
    })

Fails with:

TypeError: Type is not JSON serializable: pydantic_core._pydantic_core.Url

It seems like we should default to using .model_dump(mode='json')?

You could change example to this:

@api.get("/test", response=SomeModel)
def example(request):
    return SomeModel.model_validate({
        "url": "custom-protocol://foo/bar"
    }).model_dump(mode='json')

But this is a shame: we end up calling model_dump and model_validate multiple times (which can be expensive with a lot of data), and we loose type hints on the function.

Versions (please complete the following information):

  • Python version: 3.11
  • Django version: 5.1
  • Django-Ninja version: 1.3.0
  • Pydantic version: 2
@orf orf changed the title [BUG] model_dump defaults to Python output [BUG] model_dump defaults to mode=python Aug 21, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant