Skip to content

Conversation

rimi0108
Copy link

@rimi0108 rimi0108 commented Oct 4, 2025

…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:

  1. Primary keys are not omitted from the serialized object dump.
  2. Foreign keys fall back to standard integer PK serialization instead of list-based natural key formats.

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

  • This PR targets the main branch.
  • The commit message is written in past tense, mentions the ticket number, and ends with a period.
  • I have checked the "Has patch" ticket flag in the Trac system.
  • I have added or updated relevant tests.
  • I have added or updated relevant docs, including release notes if applicable.
  • I have attached screenshots in both light and dark modes for any UI changes.

…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:
1. Primary keys are not omitted from the serialized object dump.
2. Foreign keys fall back to standard integer PK serialization instead
   of list-based natural key formats.

This addresses a usability regression where subclasses could not cancel
natural key inheritance. Thanks Jonas Dittrich for the report
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.

2 participants