Skip to content

Conversion of models.JSONField #267

@benoit9126

Description

@benoit9126

Hi!

I am using ninja_extra.ModelConfig class in order to generate an API for a Django model which has a models.JSONField field. The converter internally used by ninja_schema to get a Pydantic field from the Django field is:

# from ninja_schema.orm.utils.converter.py

@t.no_type_check
@convert_django_field.register(models.JSONField)
def convert_field_to_json_string(
    field: Field, **kwargs: DictStrAny
) -> t.Tuple[t.Type, PydanticField]:
    python_type = Json
    if field.null:
        python_type = t.Optional[Json]
    return construct_field_info(python_type, field)

Unfortunately, the Json Pydantic field expects serialized data as input. When reading an object with a models.JSONField field from the database, Django retrieves a dict (not string, bytes or bytearray) for this field. This leads to this validation error from Pydantic:

JSON input should be string, bytes or bytearray [type=json_type, input_value={'values': [1], 'numbers': []}, input_type=dict]

I think that the Pydantic Json field is perfect for a create_schema or update_schema as their data comes from the HTTP request. But, in the case of a retrieve_schema, the python_type should be a dict (not Json) as there is no conversion to perform.

NB: I have manually defined a retrieve_schema using the dict field to bypass this problem.

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