Skip to content

Render decimals as numbers in the OpenAPI YAML schema - #10112

Open
LindseyZ1205 wants to merge 1 commit into
encode:mainfrom
LindseyZ1205:fix/openapi-yaml-decimal
Open

LindseyZ1205 wants to merge 1 commit into
encode:mainfrom
LindseyZ1205:fix/openapi-yaml-decimal

Conversation

@LindseyZ1205

Copy link
Copy Markdown
Contributor

manage.py generateschema (and the OpenAPIRenderer) writes Decimal values in the schema as Python-specific YAML tags. For example, a model field such as

price = models.DecimalField(
    max_digits=6, decimal_places=2,
    validators=[MinValueValidator(Decimal('0.01')), MaxValueValidator(Decimal('500'))],
)

gives

          maximum: !!python/object/apply:decimal.Decimal
          - '500'
          minimum: !!python/object/apply:decimal.Decimal
          - '0.01'

which YAML loaders other than PyYAML's unsafe one can't read: yaml.safe_load() fails with "could not determine a constructor for the tag 'tag:yaml.org,2002:python/object/apply:decimal.Decimal'". Since #9997, a model DecimalField with a decimal default ends up in the schema in the same way.

This is the same problem as #8063 for timedelta, which was fixed with a representer for the YAML Dumper. This adds one for Decimal, which renders the value as a number, as the JSONEncoder of the JSONOpenAPIRenderer does (maximum: 500.0, minimum: 0.01).

I added a DecimalField with these validators to ExampleValidatedSerializer, and a YAML rendering test next to the timedelta one; the test fails without the change. The full test suite passes with Django 6.1.2 and Django main, and flake8, isort and codespell pass on the changed files.

The `OpenAPIRenderer` dumped `Decimal` values, such as the limits of a
`MaxValueValidator(Decimal('500'))` on a `DecimalField`, as
`!!python/object/apply:decimal.Decimal` tags, which YAML loaders other
than PyYAML's unsafe one can't read. Render them as numbers, as the
`JSONEncoder` used by the `JSONOpenAPIRenderer` does.
@auvipy
auvipy self-requested a review November 19, 2026 06:03

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant