datamodel-code-generator icon indicating copy to clipboard operation
datamodel-code-generator copied to clipboard

fix: respect `--extra-fields` option in pydantic v2 models

Open cosmo-grant opened this issue 5 months ago • 2 comments

My PR #2417 was incomplete: the --extra-fields option was not respected in pydantic v2 models.

For example, given the schema

{
  "title": "Test",
  "type": "object",
  "required": [
    "foo"
  ],
  "properties": {
    "foo": {
      "type": "object",
      "properties": {
        "x": {
          "type": "integer"
        }
      }
    }
  }
}

when I run on 0.31.0:

% datamodel-codegen --input example.json --output-model-type pydantic_v2.BaseModel --input-file-type jsonschema --extra-fields forbid

it outputs

# generated by datamodel-codegen:
#   filename:  simple.json
#   timestamp: 2025-06-16T16:09:32+00:00

from __future__ import annotations

from typing import Optional

from pydantic import BaseModel


class Foo(BaseModel):
    x: Optional[int] = None


class Test(BaseModel):
    foo: Foo

which disregards --extra-fields forbid.

This PR fixes that and adds some unit tests.

Fixes #2422

cosmo-grant avatar Jun 16 '25 16:06 cosmo-grant

Codecov Report

All modified and coverable lines are covered by tests :white_check_mark:

Project coverage is 98.13%. Comparing base (0886c0e) to head (1863f7f). Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #2423   +/-   ##
=======================================
  Coverage   98.12%   98.13%           
=======================================
  Files          66       66           
  Lines        8231     8242   +11     
  Branches      823      827    +4     
=======================================
+ Hits         8077     8088   +11     
  Misses        115      115           
  Partials       39       39           
Flag Coverage Δ
unittests 98.13% <100.00%> (+<0.01%) :arrow_up:

Flags with carried forward coverage won't be shown. Click here to find out more.

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.

:rocket: New features to boost your workflow:
  • :snowflake: Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

codecov[bot] avatar Jun 16 '25 16:06 codecov[bot]

CodSpeed Performance Report

Merging #2423 will not alter performance

Comparing cosmo-grant:fix_extra_fields_pydantic_v2 (1863f7f) with main (0886c0e)

Summary

✅ 32 untouched benchmarks

codspeed-hq[bot] avatar Jun 16 '25 16:06 codspeed-hq[bot]