Fixed #35729 -- Enabled natural key serialization opt-out for subclasses. #19919
+226
−10
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
…ses.
Refactored serialization logic to allow models inheriting a 'natural_key' method (e.g., AbstractBaseUser) to explicitly opt out by returning None or (obj.pk,) from the method.
The fix ensures that:
This addresses a usability regression where subclasses could not cancel natural key inheritance. Thanks Jonas Dittrich for the report
Trac ticket number
ticket-35729
Branch description
This branch implements a robust opt-out mechanism for natural key serialization in Django.
Issue Overview
Models that inherit the natural_key method (like subclasses of AbstractBaseUser) were previously unable to prevent Django's serialization framework from omitting their primary key (pk) when dumping data with natural_primary_keys=True. This occurred because the framework only checked for the method's existence rather than its result, leading to data loss upon deserialization.
Proposed Changes
The serialization logic in PythonSerializer and XMLSerializer has been refactored to check the return value of natural_key(). The system now treats the following as explicit opt-out signals, forcing a fallback to standard integer PK serialization:
return None (The canonical opt-out signal).
return () (An empty/falsy value).
return (self.pk,) (A common user workaround).
This ensures that the primary key is always included in the dump, and Foreign Keys are serialized as standard integers, fully resolving the usability bug.
Checklist
main
branch.