Skip to content

[BUG] model_dump defaults to mode=python #1273

Open
@orf

Description

@orf

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions