Skip to content

Change errors for list serializers (many=True) to dict format - #9837

Merged
browniebroke merged 8 commits into
encode:mainfrom
p-r-a-v-i-n:fix/7279-listserializer-errors
Jul 25, 2026
Merged

browniebroke merged 8 commits into
encode:mainfrom
p-r-a-v-i-n:fix/7279-listserializer-errors

Conversation

@p-r-a-v-i-n

@p-r-a-v-i-n p-r-a-v-i-n commented Nov 26, 2025 •

Copy link
Copy Markdown
Contributor

Fix #7279

This pr changes the formatting of list serializer errors.

  • previously list serializer returing errors in list format.
  • It was adding empty dict ("{}") for every valid item in the list
  • this format was not consistent with the list field error format.
  • this is previous sample format
{
    'list_serializer': [
        {},
        {'num': [ErrorDetail(string='Must be a valid boolean.', code='invalid')]},
        {},
        {'num': [ErrorDetail(string='Must be a valid boolean.', code='invalid')]}
    ],
    
    'list_field': {
        1: [ErrorDetail(string='This dictionary may not be empty.', code='empty')],
        3: [ErrorDetail(string='This dictionary may not be empty.', code='empty')]
    }
}

Changes:

  • returning dict instead of the list bcs :

    • it is easier to handle dict compare to list for clients
    • if there 100 items in which 99 are valid then it would add 99 "{}" in the list.
    • both list field and list serializer errors are consistent.
  • here is the updated sample format

{
    'list_serializer': {
        0: {'num': [ErrorDetail(string='Must be a valid boolean.', code='invalid')]},
        1: {'num': [ErrorDetail(string='Must be a valid boolean.', code='invalid')]}
    },
    
    'list_field': {
        1: [ErrorDetail(string='This dictionary may not be empty.', code='empty')],
        3: [ErrorDetail(string='This dictionary may not be empty.', code='empty')]
    }
}

for clarity I can add more example if needed.

@p-r-a-v-i-n
p-r-a-v-i-n marked this pull request as draft November 26, 2025 05:59
@p-r-a-v-i-n
p-r-a-v-i-n marked this pull request as ready for review November 26, 2025 06:45

@browniebroke browniebroke left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

here is the updated sample format

{
    'list_serializer': {
        0: {'num': [ErrorDetail(string='Must be a valid boolean.', code='invalid')]},
        1: {'num': [ErrorDetail(string='Must be a valid boolean.', code='invalid')]}
    },
    
    'list_field': {
        1: [ErrorDetail(string='This dictionary may not be empty.', code='empty')],
        3: [ErrorDetail(string='This dictionary may not be empty.', code='empty')]
    }
}

The top level structure is indeed a dict, but the values of this dict aren't consistent: in the list serializer case, they are dict[str, list[ErrorDetail]] while in the list field they are list[ErrorDetail].

Is that right or am I missing something?

EDIT: I think I got it, ignore this comment

Comment thread rest_framework/serializers.py Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR changes the error format for ListSerializer to use a dict-based structure (with indices as keys) instead of a list-based structure (with empty dicts for valid items). This improves consistency with how ListField handles errors and makes error handling easier for API clients.

  • Changed error structure from list to dict format for ListSerializer
  • Only invalid item indices are included in error dict (no empty placeholders for valid items)
  • Ensures consistency between ListSerializer and ListField error formats

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 2 comments.

File Description
rest_framework/serializers.py Modified to_internal_value to collect errors in a dict keyed by index instead of a list with empty dicts for valid items
tests/test_serializer_lists.py Added comprehensive tests for dict-based error format and consistency between ListSerializer and ListField
tests/test_serializer_bulk_update.py Updated expected error format in tests to use dict structure with indices as keys

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread tests/test_serializer_lists.py Resolved
Comment thread tests/test_serializer_lists.py Resolved
@browniebroke

Copy link
Copy Markdown
Collaborator

Looks good to me as well, but that's probably going to be seen as a breaking change so will need to wait for 3.18 IMO

I suggest we hold off merging for a bit to let us release any potential bug fixes for 3.17.x... What do you think?

@browniebroke browniebroke added this to the 3.18 milestone Apr 10, 2026
@Natgho

Natgho commented Apr 10, 2026

Copy link
Copy Markdown
Contributor

Looks good to me as well, but that's probably going to be seen as a breaking change so will need to wait for 3.18 IMO

I suggest we hold off merging for a bit to let us release any potential bug fixes for 3.17.x... What do you think?

That makes sense, because this situation will cause many of the error tests in projects using DRF to fail.

@p-r-a-v-i-n

Copy link
Copy Markdown
Contributor Author

I'm agreed with @browniebroke . It was there in my mind when we were releasing 3.17. but I missed it. I should have pinged you both about this.

@browniebroke browniebroke changed the title Addresses #7279 : consistent formatting btw list serializers and list field errors Change errors for list serializers (many=True) to dict format Jul 25, 2026
@browniebroke
browniebroke merged commit e6f4d85 into encode:main Jul 25, 2026
7 checks passed
@browniebroke

Copy link
Copy Markdown
Collaborator

Thanks!

@Kub-AT

Kub-AT commented Aug 28, 2026

Copy link
Copy Markdown
Contributor

I like the change itself, but changing the error response shape this much feels a bit abrupt. For something this fundamental, it would be much nicer to have a deprecation period or an opt-in first, and only switch the default in the next release.

@browniebroke

Copy link
Copy Markdown
Collaborator

See #10018

(Still waiting for a PR to review AFAIK)

feanil added a commit to openedx/openedx-platform that referenced this pull request Aug 31, 2026
DRF 3.18.0 changes how ListSerializer (many=True) reports child validation
errors: a list padded with empty dicts becomes a dict keyed by the index of
each failing item, with passing items omitted. That flips the JSON type of
the error response body from an array to an object:

  3.17.2  [{},{"code":["This field is required."]},{}]
  3.18.0  {"1":{"code":["This field is required."]}}

Several write endpoints hand these errors straight back to the caller, so
their error responses change shape. Those responses are part of our API
contract, and only one test in the repo pinned the format, so the change
would have gone out silently.

Hold at <3.18 so the migration can be made deliberately, with the usual
consideration for API consumers, rather than riding in on a routine
requirements bump. Resolves to 3.17.2, which retains the old shape.

Upstream change: encode/django-rest-framework#9837
Issue for unpinning: #39048

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
feanil added a commit to openedx/openedx-platform that referenced this pull request Aug 31, 2026
DRF 3.18.0 changes how ListSerializer (many=True) reports child validation
errors: a list padded with empty dicts becomes a dict keyed by the index of
each failing item, with passing items omitted. That flips the JSON type of
the error response body from an array to an object:

  3.17.2  [{},{"code":["This field is required."]},{}]
  3.18.0  {"1":{"code":["This field is required."]}}

Several write endpoints hand these errors straight back to the caller, so
their error responses change shape. Those responses are part of our API
contract, and only one test in the repo pinned the format, so the change
would have gone out silently.

Hold at <3.18 so the migration can be made deliberately, with the usual
consideration for API consumers, rather than riding in on a routine
requirements bump. Resolves to 3.17.2, which retains the old shape.

Upstream change: encode/django-rest-framework#9837
Issue for unpinning: #39048

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
feanil added a commit to openedx/openedx-platform that referenced this pull request Aug 31, 2026
DRF 3.18.0 changes how ListSerializer (many=True) reports child validation
errors: a list padded with empty dicts becomes a dict keyed by the index of
each failing item, with passing items omitted. That flips the JSON type of
the error response body from an array to an object:

  3.17.2  [{},{"code":["This field is required."]},{}]
  3.18.0  {"1":{"code":["This field is required."]}}

Several write endpoints hand these errors straight back to the caller, so
their error responses change shape. Those responses are part of our API
contract, and only one test in the repo pinned the format, so the change
would have gone out silently.

Hold at <3.18 so the migration can be made deliberately, with the usual
consideration for API consumers, rather than riding in on a routine
requirements bump. Resolves to 3.17.2, which retains the old shape.

Upstream change: encode/django-rest-framework#9837
Issue for unpinning: #39048

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
intgr pushed a commit to typeddjango/djangorestframework-stubs that referenced this pull request Sep 23, 2026
* Allow int keys in exception details and ListSerializer.errors

DRF keys error mappings by list index, not only by field name:
`ListField.run_child_validation` has always raised `ValidationError`
with an index-keyed dict, and since DRF 3.18 `ListSerializer.
to_internal_value` does too (encode/django-rest-framework#9837).
`_get_error_details` passes mapping keys through untouched, so those
`int` keys reach `.detail`, `.get_codes()` and `.get_full_details()`.

Widen the detail key type to `str | int` in `_Detail`, `_ErrorCodes`,
`_ErrorFullDetails` and `ValidationError.detail`. On the input side,
`Mapping` is invariant in its key type, so `_APIExceptionInput` gains a
second `Mapping[int, ...]` member rather than a single
`Mapping[str | int, ...]`, which would have rejected plain
`dict[str, ...]` values.

The same DRF change also makes `ListSerializer.errors` return a
`ReturnDict` when the errors are index-keyed, so its return type
becomes `ReturnDict | ReturnList`.

Fixes #1056

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

---------

Co-authored-by: João Pedro Sousada Silva e Sousa <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
HosseinSayyedMousavi pushed a commit to HosseinSayyedMousavi/django-rest-framework that referenced this pull request Oct 8, 2026
khvn26 added a commit to Flagsmith/flagsmith that referenced this pull request Nov 5, 2026
DRF 3.18 changed many=True serializer errors to index-keyed dicts (encode/django-rest-framework#9837). Set LIST_SERIALIZER_ERRORS_AS_DICT to False to keep the existing API error contract until clients are migrated; the setting is removed in DRF 3.20.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Development

Successfully merging this pull request may close these issues.

ListField validation errors are inconsistent with ListSerializer

6 participants