Open
Description
Describe the bug
All calls to BaseModel.model_dump
use the default mode argument, which is python
and not json
. For example:
django-ninja/ninja/operation.py
Line 271 in b655532
django-ninja/ninja/responses.py
Line 23 in b655532
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
Labels
No labels