Skip to content

[BUG] Default attributes within BaseModel not used for ninja.Query #1581

@HeyHugo

Description

@HeyHugo

Default attributes are not used when query params are parsed for pydantic BaseModel. I faced this issue upgrading a larger codebase from an old django-ninja version to a more recent.

from pydantic import BaseModel

class Filter(BaseModel):
    foo: int = 1

@api.get("/test")
def test(request, filters: Filter = Query(...)):
    ...

Here's a one liner showing the issue (showing BaseModel vs Schema), ready to paste (requiring only uv):

uv run --with "git+https://github.com/vitalik/django-ninja@master" python <<'PY'
import os
from django.conf import settings

os.environ["NINJA_SKIP_REGISTRY"] = "yes"

settings.configure(
  DEBUG=True,
  SECRET_KEY="demo",
  ROOT_URLCONF=__name__,
  ALLOWED_HOSTS=["*"],
  INSTALLED_APPS=["django.contrib.auth", "django.contrib.contenttypes"],
  MIDDLEWARE=[],
)

import django
django.setup()

from ninja import NinjaAPI, Query, Schema
from ninja.testing.client import TestClient
from pydantic import BaseModel

class FilterBaseModel(BaseModel):
  start: int
  optional: int = 42

class FilterSchema(Schema):
  start: int
  optional: int = 42

api = NinjaAPI(urls_namespace="demo-cli")

@api.get("/basemodel")
def basemodel_view(request, filters: FilterBaseModel = Query(...)):
  return {"filters": filters.dict()}

@api.get("/schema")
def schema_view(request, filters: FilterSchema = Query(...)):
  return {"filters": filters.dict()}

urlpatterns = api.urls

client = TestClient(api)
params = "start=1"

resp_base = client.get(f"/basemodel?{params}")
resp_schema = client.get(f"/schema?{params}")

print("BaseModel:", resp_base.status_code, resp_base.json())
print("Schema:", resp_schema.status_code, resp_schema.json())
PY

Output using master version:

BaseModel: 422 {'detail': [{'type': 'int_type', 'loc': ['query', 'optional'], 'msg': 'Input should be a valid integer'}]}
Schema: 200 {'filters': {'start': 1, 'optional': 42}}

Change version from @master to @v0.22.2 to see last functioning version

I saw #1564 but not sure if this is the same thing. I tried with all the versions mentioned there they all have this issue still.

Versions:

  • Python version: 3.13.1
  • Django version: 5.2.7
  • Django-Ninja version: All version from v1.0 to master
  • Pydantic version: 2.12.3

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