Repository navigation
Fix list serializer on unique constraint validator - #10033
Conversation
There was a problem hiding this comment.
🟢 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, descriptiveRuntimeErrorfor unsupported multi-update usage. - Extend validator test coverage for
many=Truecreate/update scenarios (including requiredrun_child_validation()override behavior). - Document how to override
ListSerializer.run_child_validation()to setchild.instancefor 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.
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
|
@auvipy Description added , And I see doc is also updated ! PR is ready for review now ! |
There was a problem hiding this comment.
🔵 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_dataas the entire list forwarded bymany_init(), so child-level validation that readsself.initial_datareceives the wrong object. The established per-item override sets both values before delegating (rest_framework/serializers.py:658-667, also exercised intests/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
There was a problem hiding this comment.
🟡 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
There was a problem hiding this comment.
🟢 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
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
* 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]>
Fixes #9484
Problem
Since 3.15 (#7438), uniqueness validators run for serializers built from models
using
UniqueConstraint. When a serializer is used withmany=Trueand aqueryset (or list) is passed as
instance— i.e. a multiple update — thesevalidators crash with a confusing error:
The root cause:
many_init()forwards the whole queryset/list to the childserializer as its
.instance, and the validators'exclude_current_instance()then calls
instance.pkon it while trying to exclude the object being updatedfrom the uniqueness check.
UniqueTogetherValidatoralready raised a descriptiveRuntimeErrorfor thiscase, but
UniqueValidatorand theUniqueForDateValidatorfamily still hitthe raw
AttributeError.Changes
rest_framework/validators.py: extracted the existing check fromUniqueTogetherValidator.__call__into a shared_check_single_instance()helper, and applied it to
UniqueValidatorandBaseUniqueForValidator(covering
UniqueForDate/Month/YearValidator) as well. All uniquenessvalidators now raise the same clear
RuntimeErrorexplaining thatListSerializer.run_child_validation()must be overridden to setchild.instanceper item, instead of an opaqueAttributeError.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 instanceby
pkso unchanged values are not reported as conflicts with themselves.tests/test_validators.py: added tests for all three validator familiesverifying that (a)
many=Truecreate still validates uniqueness normally,(b) a multiple update with a queryset or list
instanceraises thedescriptive
RuntimeError, and (c) with the documentedrun_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
many=Truecreate, or for single-instance updates.automatic per-item O(N) lookup is introduced; the unsupported case now
fails loudly with actionable guidance, and the supported path is documented.