Skip to content

Nullable required fields should not have default value#2520

Merged
gaborbernat merged 21 commits intokoxudaxi:mainfrom
raymondbutcher:required-nullable-annotated
Dec 20, 2025
Merged

Nullable required fields should not have default value#2520
gaborbernat merged 21 commits intokoxudaxi:mainfrom
raymondbutcher:required-nullable-annotated

Conversation

@raymondbutcher
Copy link
Copy Markdown
Contributor

@raymondbutcher raymondbutcher commented Oct 17, 2025

Hi. Thanks for the project!

My OpenAPI spec has some fields as both nullable and required, but they are generating models with default values like this:

class Person(BaseModel):
    first_name: Annotated[str | None, Field(alias='firstName')] = None
    last_name: Annotated[str | None, Field(alias='lastName')] = None

Those default values make the fields optional, so it's not working as expected.

This fix also highlighted what looks to be a bug in an existing test that is checking for an incorrect result:

Summary by CodeRabbit

  • Bug Fixes

    • Stricter handling of default-value assignment for optional/nullable fields; some optional fields no longer receive an implicit None default.
  • New Features

    • Improved OpenAPI/model generation for nullable-but-required fields using annotations; adds a Person schema example.
  • Documentation

    • Updated Pydantic v2 example to reflect new optional-field defaults.
  • Tests

    • Added tests for nullable-required field generation (duplicate test entry present).

✏️ Tip: You can customize this high-level summary in your review settings.

Comment thread src/datamodel_code_generator/model/template/pydantic_v2/BaseModel.jinja2 Outdated
@ilovelinux
Copy link
Copy Markdown
Collaborator

This PR closes the following issues:

Please link this PR with the issue as described here. Thanks!

@gaborbernat gaborbernat enabled auto-merge (squash) November 3, 2025 14:07
@codspeed-hq
Copy link
Copy Markdown

codspeed-hq Bot commented Nov 3, 2025

CodSpeed Performance Report

Merging #2520 will not alter performance

Comparing raymondbutcher:required-nullable-annotated (bc8895a) with main (590e568)

Summary

✅ 52 untouched
⏩ 10 skipped1

Footnotes

  1. 10 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.

@koxudaxi
Copy link
Copy Markdown
Owner

@raymondbutcher
Thank you for creating the PR.
Could you plesae fix the unittest ?

    raise rewrite_traceback_stack(source=source)
  File "/Users/runner/work/datamodel-code-generator/datamodel-code-generator/.tox/3.11/lib/python3.11/site-packages/datamodel_code_generator/model/template/pydantic_v2/BaseModel.jinja2", line 35, in template
    {%- if not field.required and (field.represented_default != 'None' or not field.strip_default_none) or field.data_type.is_optional)
    ^^^^^^^^^^^^^^^^^^^^^^^^^
jinja2.exceptions.TemplateSyntaxError: unexpected ')'```

Comment thread src/datamodel_code_generator/model/template/pydantic_v2/BaseModel.jinja2 Outdated
@ilovelinux ilovelinux linked an issue Nov 17, 2025 that may be closed by this pull request
@codecov
Copy link
Copy Markdown

codecov Bot commented Nov 29, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.33%. Comparing base (590e568) to head (bc8895a).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #2520   +/-   ##
=======================================
  Coverage   99.33%   99.33%           
=======================================
  Files          81       81           
  Lines       11478    11480    +2     
  Branches     1367     1367           
=======================================
+ Hits        11402    11404    +2     
  Misses         45       45           
  Partials       31       31           
Flag Coverage Δ
unittests 99.33% <100.00%> (+<0.01%) ⬆️

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

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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

@koxudaxi koxudaxi requested a review from ilovelinux November 29, 2025 13:44
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Dec 18, 2025

Walkthrough

Tightened the Pydantic v2 BaseModel template default-emission condition; removed several emitted = None defaults in generated fixtures; added an OpenAPI schema, its generated model using Annotated, and a test (duplicated in the diff).

Changes

Cohort / File(s) Summary
Template logic update
src/datamodel_code_generator/model/template/pydantic_v2/BaseModel.jinja2
Tightened the conditional that decides when to emit a field default. Now requires not field.has_default_factory_in_field and not field.required, and only emits defaults when (field.represented_default != 'None' or not field.strip_default_none or field.data_type.is_optional).
Removed explicit None defaults
tests/data/expected/main/jsonschema/null_and_array_v2.py, tests/data/expected/main/openapi/unquoted_null.py, docs/cli-reference/model-customization.md
Removed = None defaults from optional field declarations (e.g., `list[Any]
New OpenAPI schema
tests/data/openapi/nullable_required_annotated.yaml
Added Person schema with firstName and lastName marked nullable: true and included in required.
New generated model
tests/data/expected/main/openapi/nullable_required_annotated.py
Added Pydantic v2 model Person using `Annotated[str
Test additions
tests/main/openapi/test_main_openapi.py
Added test_main_openapi_nullable_required_annotated to validate generation with options (pydantic_v2.BaseModel, --strict-nullable, --use-annotated, --use-union-operator, --snake-case-field). The function appears duplicated in the diff.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Inspect BaseModel.jinja2 conditional logic for edge cases: optional unions, strip_default_none, and default factories.
  • Verify generated files (tests/data/expected/...) reflect intended semantics and imports for Annotated/Field.
  • Remove or consolidate the duplicated test in tests/main/openapi/test_main_openapi.py.
  • Confirm documentation example in docs/cli-reference/model-customization.md matches template output.

Poem

🐰
I nibble at templates, tighten a seam,
Defaults sit straighter, neat as a dream.
Nullable blooms now stand on their own,
New models and tests in the burrow are shown,
A carrot-code hop — light, quick, and keen! 🥕

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title accurately summarizes the main change: preventing nullable required fields from having default values, which directly addresses the core issue in the changeset.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 02a50d3 and d0913e1.

📒 Files selected for processing (1)
  • docs/cli-reference/model-customization.md (1 hunks)
🔇 Additional comments (1)
docs/cli-reference/model-customization.md (1)

3154-3154: Documentation correctly reflects required nullable field fix.

The change aligns with the PR objective: required nullable fields no longer receive default values. In Pydantic v2, the field items (marked as required despite accepting null) is now correctly generated without = None, making it a true required field at the type level.

However, verify that the Pydantic v1 output (lines 3131-3132) is also consistent—it shows items: list[Any] | None without a default, which is correct for a required field.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@koxudaxi
Copy link
Copy Markdown
Owner

koxudaxi commented Dec 18, 2025

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Dec 18, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@koxudaxi
Copy link
Copy Markdown
Owner

@ilovelinux Can you review the PR again?

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Dec 18, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@gaborbernat gaborbernat merged commit 4423a49 into koxudaxi:main Dec 20, 2025
38 checks passed
@Paillat-dev
Copy link
Copy Markdown

Thank You !

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG]: All of the fields have a None default

5 participants