Hi, I’m working on ticket 36259 with Djangonaut Space. I’d like your view on the intended behavior before I go further.
The ticket lists four cases where a new model instance (built in Python, not loaded from the database) has a primary key set, by hand or from a default:
- Saving an object that points to it.
- Reading an unloaded generated field.
- Passing it to
QuerySet.contains(). - Passing it to a related
filter()orexclude().
Draft PR 22182 now covers all four:
- Case 2 is changed now: when no row matches, Django raises
AttributeErrorinstead ofDoesNotExist. - Cases 1, 3 and 4 only warn for now (
RemovedInDjango2029Warning). Results don’t change. The docs suggest raisingValueErrorin Django 2029, but that date is only a proposal.
The check uses _state.adding. It tells how the Python object was made, not whether a row exists. So valid code warns too. With Parent (a CharField primary key) and Child (a ForeignKey to Parent):
stored = Parent.objects.create(id="existing")
ref = Parent(pk=stored.pk) # _state.adding is True
Child.objects.create(parent=ref) # works, now warns
Parent.objects.contains(ref) # True, now warns
Child.objects.filter(parent=ref).exists() # True, now warns
It also warns when the related row is saved later in the same transaction (on databases that defer foreign key checks), in a pre_save handler or custom clean() that filters by a new instance with a default UUID key, and with deserialized instances. Reverse related managers, prefetching, inline formsets and deletion don’t warn.
I read the January thread “Allow querying RelatedManagers on unsaved objects” and Jacob’s review on PR 19275. Both point out the cost of breaking valid code, so I don’t want to assume this direction is right.
Questions:
- Should a primary key that points to an existing row keep working for saves,
contains()and related filters, whatever_state.addingsays? - If Django should be stricter, what problem would justify breaking that code?
- Can the generated-field change go ahead on its own while the rest is decided?
The new tests pass on SQLite, PostgreSQL, MySQL and Oracle. Details are in the PR.
AI use: I used OpenAI Codex CLI, OpenCode with GPT-6.1 Sol, and Claude Code with Claude Opus 5.5 for research, code, tests and docs, and to help write this post. I reviewed the output myself.