Skip to content

fix: use JsonValue for models.JSONField to accept dict input#58

Open
yulinfeng000 wants to merge 1 commit into
eadwinCode:masterfrom
yulinfeng000:fix/jsonfield-jsonvalue
Open

fix: use JsonValue for models.JSONField to accept dict input#58
yulinfeng000 wants to merge 1 commit into
eadwinCode:masterfrom
yulinfeng000:fix/jsonfield-jsonvalue

Conversation

@yulinfeng000
Copy link
Copy Markdown

Summary

Fixes the json_type ValidationError raised when a ModelSchema built from a Django model containing JSONField is populated from a database row.

  • convert_postgres_field_to_string and convert_field_to_json_string now produce pydantic.JsonValue instead of pydantic.Json.
  • JsonValue accepts the Python dict/list values the Django ORM returns; Json required a serialized string/bytes payload, which is the source of the bug.
  • Updated tests/test_v2_pydantic/test_converters.py::test_django_31_fields to assert the new (correct) behavior: dict input is now valid, and the JSON schema fragment is JsonValue's $ref form.

Related issue

Refs eadwinCode/django-ninja-extra#267

Note on Pydantic v1 compatibility

pydantic.JsonValue was introduced in Pydantic 2.5. This PR's top-level import will fail under Pydantic v1, which is still permitted by pyproject.toml (pydantic>=1.7.4,...,<3.0.0).

I'm happy to follow up with either:

  1. Gate by version — keep Json (or plain dict) for Pydantic v1 behind an IS_PYDANTIC_V1 branch, OR
  2. Drop v1 support — bump the floor to pydantic>=2.5 in pyproject.toml and remove the v1 branches.

Let me know which direction you prefer and I'll send a follow-up commit.

Test plan

  • pytest tests/test_v2_pydantic/test_converters.py::test_django_31_fields passes
  • ruff check ninja_schema tests clean on the modified files
  • Manual: ModelSchema with a JSONField accepts {"any": "data"} directly without raising ValidationError
  • pytest tests/test_v1_pydantic/... — see "Note on Pydantic v1" above

Pydantic's Json type expects serialized strings, so response schemas
built from Django models with JSONField fail with json_type
ValidationError when the ORM returns dicts. Switch the converter for
both PostgreSQL JSON/HStore fields and Django 3.1+ models.JSONField
to JsonValue, which accepts JSON-compatible Python objects directly.

Updated the corresponding v2 test to assert the new (correct) behavior.

Refs eadwinCode/django-ninja-extra#267
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

Successfully merging this pull request may close these issues.

1 participant