Skip to content

Fix list serializer on unique constraint validator - #10033

Merged
auvipy merged 5 commits into
encode:mainfrom
MehrazRumman:issue9484
Sep 6, 2026
Merged

auvipy merged 5 commits into
encode:mainfrom
MehrazRumman:issue9484

Conversation

@MehrazRumman

@MehrazRumman MehrazRumman commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #9484

Problem

Since 3.15 (#7438), uniqueness validators run for serializers built from models
using UniqueConstraint. When a serializer is used with many=True and a
queryset (or list) is passed as instance — i.e. a multiple update — these
validators crash with a confusing error:

AttributeError: 'QuerySet' object has no attribute 'pk'

The root cause: many_init() forwards the whole queryset/list to the child
serializer as its .instance, and the validators' exclude_current_instance()
then calls instance.pk on it while trying to exclude the object being updated
from the uniqueness check.

UniqueTogetherValidator already raised a descriptive RuntimeError for this
case, but UniqueValidator and the UniqueForDateValidator family still hit
the raw AttributeError.

Changes

  • rest_framework/validators.py: extracted the existing check from
    UniqueTogetherValidator.__call__ into a shared _check_single_instance()
    helper, and applied it to UniqueValidator and BaseUniqueForValidator
    (covering UniqueForDate/Month/YearValidator) as well. All uniqueness
    validators now raise the same clear RuntimeError explaining that
    ListSerializer.run_child_validation() must be overridden to set
    child.instance per item, instead of an opaque AttributeError.

  • docs/api-guide/serializers.md: documented the limitation in the
    "multiple updates" section, with an example run_child_validation()
    override (for a queryset instance) that resolves each item's instance
    by pk so unchanged values are not reported as conflicts with themselves.

  • tests/test_validators.py: added tests for all three validator families
    verifying that (a) many=True create still validates uniqueness normally,
    (b) a multiple update with a queryset or list instance raises the
    descriptive RuntimeError, and (c) with the documented
    run_child_validation() override, bulk updates validate correctly —
    an item keeping its own value passes, while a value colliding with a
    different instance is rejected.

Notes

  • No behavior change for many=True create, or for single-instance updates.
  • Per the discussion in List Serializer Breaks on Unique Constraint Validator #9484, validation is not silently skipped and no
    automatic per-item O(N) lookup is introduced; the unsupported case now
    fails loudly with actionable guidance, and the supported path is documented.

@MehrazRumman
MehrazRumman marked this pull request as draft September 5, 2026 18:02
@auvipy
auvipy requested a lite review from Copilot September 6, 2026 06:27

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.

🟢 Approval recommended

The behavioral change is narrowly scoped, covered by targeted tests, and improves error clarity without introducing obvious correctness risks.

Pull request overview

This PR addresses #9484 by preventing uniqueness-related validators from crashing during many=True validation when the serializer’s instance is a queryset/list, replacing an AttributeError failure mode with a clear RuntimeError and guidance for supporting multiple updates.

Changes:

  • Add a shared guard (_check_single_instance) and apply it across uniqueness validator families to raise a consistent, descriptive RuntimeError for unsupported multi-update usage.
  • Extend validator test coverage for many=True create/update scenarios (including required run_child_validation() override behavior).
  • Document how to override ListSerializer.run_child_validation() to set child.instance for uniqueness validation during multiple updates.
File summaries
File Description
tests/test_validators.py Adds regression tests for uniqueness validators under many=True create/update flows and the expected RuntimeError guidance.
rest_framework/validators.py Introduces _check_single_instance and uses it in uniqueness validators to avoid instance.pk crashes for multi-update.
docs/api-guide/serializers.md Documents required run_child_validation() override behavior for uniqueness validators during multiple updates.
Review details
  • Files reviewed: 3/3 changed files
  • Comments generated: 1
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread docs/api-guide/serializers.md Resolved
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
@MehrazRumman
MehrazRumman marked this pull request as ready for review September 6, 2026 07:20
@MehrazRumman

Copy link
Copy Markdown
Contributor Author

@auvipy Description added , And I see doc is also updated ! PR is ready for review now !

@auvipy
auvipy requested a balanced review from Copilot September 6, 2026 07:50
@auvipy
auvipy self-requested a review September 6, 2026 07:51

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.

🔵 Needs a closer look

The documentation example has an unresolved correctness nit requiring human review.

Review details

Suppressed comments (1)

docs/api-guide/serializers.md:865

  • This override leaves child.initial_data as the entire list forwarded by many_init(), so child-level validation that reads self.initial_data receives the wrong object. The established per-item override sets both values before delegating (rest_framework/serializers.py:658-667, also exercised in tests/test_serializer_lists.py:154-184); include that assignment in this copyable example.
        def run_child_validation(self, data):
            # `.instance` is `None` for items that do not exist yet.
            self.child.instance = self.instance.filter(pk=data.get('id')).first()
            return super().run_child_validation(data)
  • Files reviewed: 3/3 changed files
  • Comments generated: 0 new
  • Review effort level: Balanced

Address review feedback: the documented override left child.initial_data as the entire list forwarded by many_init(), so child-level validation reading self.initial_data would receive the wrong object. Set it per item, matching the pattern in the run_child_validation() docstring.

Also add a test covering partial multiple updates, where unprovided field values are read from the instance set by run_child_validation().merging everything to stage
@auvipy
auvipy requested a balanced review from Copilot September 6, 2026 09:18
@auvipy auvipy added the Bug label Sep 6, 2026
@auvipy auvipy added this to the 3.18 milestone Sep 6, 2026

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.

🟡 Changes recommended

The documented override can turn ordinary invalid input into a server error.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review details
  • Files reviewed: 3/3 changed files
  • Comments generated: 1
  • Review effort level: Balanced

Comment thread docs/api-guide/serializers.md 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.

🟢 Approval recommended

The behavior change is narrowly scoped, validated by targeted tests, and improves consistency and debuggability without impacting supported create/single-update paths.

Review details
  • Files reviewed: 3/3 changed files
  • Comments generated: 1
  • Review effort level: Lite

Comment thread docs/api-guide/serializers.md Resolved
@auvipy auvipy changed the title Fixing issue #9484 Fix uniqueness validator breakage issue #9484 Sep 6, 2026
@auvipy
auvipy merged commit 4f77428 into encode:main Sep 6, 2026
7 checks passed
@MehrazRumman
MehrazRumman deleted the issue9484 branch September 6, 2026 11:17
@browniebroke browniebroke changed the title Fix uniqueness validator breakage issue #9484 Fix list serializer on unique constraint validator Sep 6, 2026
HosseinSayyedMousavi pushed a commit to HosseinSayyedMousavi/django-rest-framework that referenced this pull request Oct 8, 2026
* PR fixed and test added

* Update documentation on ListSerializer validation

* Set initial_data in run_child_validation() docs example and tests

Address review feedback: the documented override left child.initial_data as the entire list forwarded by many_init(), so child-level validation reading self.initial_data would receive the wrong object. Set it per item, matching the pattern in the run_child_validation() docstring.

Also add a test covering partial multiple updates, where unprovided field values are read from the instance set by run_child_validation().merging everything to stage

* Update uniqueness validator explanation in serializers.md


---------

Co-authored-by: Asif Saif Uddin {"Auvi":"অভি"} <[email protected]>
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.

List Serializer Breaks on Unique Constraint Validator

3 participants