# New model instances with a primary key: what should Django allow? (#36259)

**URL:** <https://forum.djangoproject.com/t/new-model-instances-with-a-primary-key-what-should-django-allow-36259/46262>\
**Category:** ORM\
**Created:** [October 24, 2026, 3:17pm UTC](https://forum.djangoproject.com/t/new-model-instances-with-a-primary-key-what-should-django-allow-36259/46262 "2026-10-24T15:17:58Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![alin-morosanu](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/alin-morosanu/32/33460_2.png) [@alin-morosanu](https://forum.djangoproject.com/u/alin-morosanu)\
**Post date:** [October 24, 2026, 3:17pm UTC](https://forum.djangoproject.com/t/new-model-instances-with-a-primary-key-what-should-django-allow-36259/46262/1 "2026-10-24T15:17:58Z")

</div>

Hi, I’m working on ticket [36259](https://code.djangoproject.com/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:

1. Saving an object that points to it.
2. Reading an unloaded generated field.
3. Passing it to `QuerySet.contains()`.
4. Passing it to a related `filter()` or `exclude()`.

Draft PR [22182](https://github.com/django/django/pull/22182) now covers all four:

- Case 2 is changed now: when no row matches, Django raises `AttributeError` instead of `DoesNotExist`.
- Cases 1, 3 and 4 only warn for now (`RemovedInDjango2029Warning`). Results don’t change. The docs suggest raising `ValueError` in 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`):

```python
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:

1. Should a primary key that points to an existing row keep working for saves, `contains()` and related filters, whatever `_state.adding` says?
2. If Django should be stricter, what problem would justify breaking that code?
3. 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.

---

<div class="post-metadata">

**Author:** ![carltongibson](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/carltongibson/32/267_2.png) [@carltongibson](https://forum.djangoproject.com/u/carltongibson)\
**Post date:** [October 25, 2026, 9:24am UTC](https://forum.djangoproject.com/t/new-model-instances-with-a-primary-key-what-should-django-allow-36259/46262/2 "2026-10-25T09:24:23Z")

</div>

I’m finding the “Case 1”, “Case 2”, and so on quite hard to follow. Neither on the PR, nor the issue description is there a motivating _Why?_ here. What are the use-cases in play, and what are the errors we’re protecting from? (The answers will follow from that.)

I will suggest that we have to be very careful with breaking changes here.

[Django 4.1 made reverse foreign key raise **`ValueError`** when calling `related managers` for unsaved objects](https://docs.djangoproject.com/en/4.1/releases/4.1/#reverse-foreign-key-changes-for-unsaved-model-instances). This was a _good change_, but it was **very disruptive** for a lot of people. Test suites, in particular, were hit hard, and it was **not** sufficiently called out in release notes for the amount of work needed to accommodate the change.

So, for each case, ensure we’re actually closing an error pattern, and make sure we document that we enough for end users.

Part of me thinks that if you’re manually setting primary keys then you really should know what you’re about. It’s not immediately clear to me that Django needs to do extra here. The [copying model instances](https://docs.djangoproject.com/en/6.1/topics/db/queries/#topics-db-queries-copy) doc have **both** nulling the pk **and** setting `_state.adding = True`, so likely a _correct_ check will inspect both.

Sorry, that’s not super helpful, but I suspect taking the time to clarify the issue/solution will make the answers (somewhat more) obvious.

---

<div class="post-metadata">

**Author:** ![alin-morosanu](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/alin-morosanu/32/33460_2.png) [@alin-morosanu](https://forum.djangoproject.com/u/alin-morosanu)\
**Post date:** [October 25, 2026, 12:04pm UTC](https://forum.djangoproject.com/t/new-model-instances-with-a-primary-key-what-should-django-allow-36259/46262/3 "2026-10-25T12:04:26Z")

</div>

Thanks Carlton, that helps. You’re right that the “why” is missing, so here it is in plain terms.

The ticket started from one test:

_ **saving an object that points to a new, unsaved instance whose primary key was set by hand.** _

- When the primary key is None, Django stops early with _“save() prohibited to prevent data loss due to unsaved related object”_.
- With a hand-set key it doesn’t, and the database raises an IntegrityError instead, sometimes only when the transaction commits.

In my tests the database always refused the row, so I found no data loss. But that depends on the database enforcing the foreign key. The clear gain is an earlier, clearer error.

For QuerySet.contains() and related filters, today they just compare the key: if a row with that key exists they find it, and if not they return no match. That’s arguably correct. I added warnings there to be consistent, but I agree that isn’t a strong enough reason to break code that works, especially after the 4.1 change you mention.

On the copying docs: good point. The warnings in the existing PR already check both (\_state.adding is True and the primary key is set). But a hand-set key that points to an existing row looks the same from Python, so I don’t think any check on the instance alone can tell them apart. A query could, but it would cost a query and still wouldn’t settle the “save the related row later” case.

The generated-field change is smaller: reading an unloaded generated field on a new instance raises AttributeError instead of DoesNotExist when no row matches. It’s still a visible change, so it needs a reason too.

So I’d like to propose:

1. Removing the warnings for contains() and related filters, unless someone knows a real bug they would catch.
2. Deciding whether saving with an unsaved related object needs any change, given that the database usually catches it.
3. Deciding whether the generated-field change is worth making on its own.

I’ll keep the existing PR as it is until we agree on the scope. Does that sound reasonable?

---

<div class="post-metadata">

**Author:** ![carltongibson](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/carltongibson/32/267_2.png) [@carltongibson](https://forum.djangoproject.com/u/carltongibson)\
**Post date:** [October 25, 2026, 3:42pm UTC](https://forum.djangoproject.com/t/new-model-instances-with-a-primary-key-what-should-django-allow-36259/46262/4 "2026-10-25T15:42:06Z")

</div>

We also want to avoid penalising the common case to catch something which you have to opt into. _Does it have a PK?_ is an easy/quick check. Yeah, maybe it’s not good enough for _This weird edge-case_, but that’s non-standard, so we want to be cautious of adding extra overhead.

> [@alin-morosanu](#):
>
> 1. Deciding whether saving with an unsaved related object needs any change, given that the database usually catches it.

So, is the issue here so bad that we need to address this here? I’m still not totally clear that we do, or don’t for that matter. (I appreciate that’s still not an actual answer — but I’d need to dig in quite a lot deeper to say so.)

I guess the follow up query is, in plain terms, why wasn’t the initial suggestion good enough for a _quick fix_? The ticket had, “My proposal is to replace such uses cases of `_is_pk_set` with `instance._state.adding` checks.” — but that led to problems, yes? So, is the fix worth the complication? (Sometimes the answer is No there.)

---

<div class="post-metadata">

**Author:** ![villager](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/villager/32/24305_2.png) [@villager](https://forum.djangoproject.com/u/villager)\
**Post date:** [October 26, 2026, 4:05am UTC](https://forum.djangoproject.com/t/new-model-instances-with-a-primary-key-what-should-django-allow-36259/46262/5 "2026-10-26T04:05:33Z")

</div>

In my opinion Django should allow the developer to set the PK and treat that instance as persisted to the database.

Everything in this example is valid, and should continue to be allowed:

```python
stored = Parent.objects.create(id=“existing”)
ref = Parent(pk=stored.pk)

Child.objects.create(parent=ref)
Parent.objects.contains(ref)
Child.objects.filter(parent=ref).exists()

```

At this point, I don’t have an opinion on how generated fields should be handled.

---

<div class="post-metadata">

**Author:** ![alin-morosanu](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/alin-morosanu/32/33460_2.png) [@alin-morosanu](https://forum.djangoproject.com/u/alin-morosanu)\
**Post date:** [November 6, 2026, 9:08am UTC](https://forum.djangoproject.com/t/new-model-instances-with-a-primary-key-what-should-django-allow-36259/46262/6 "2026-11-06T09:08:46Z")

</div>

Update:

Jacob has closed the ticket as invalid ([ticket comment](https://code.djangoproject.com/ticket/36259#comment:19)).

He agrees cases 1, 3 and 4 are intended. He sees the generated field case as intended too: with a primary key set, Django runs a query and raises `DoesNotExist` if the row is missing.

The only change he’d consider is rewording the error to say “unset primary key” instead of “unsaved object”, as a separate ticket.

Thanks @carltongibson and @villager for your input, it helped get here.

---

<div class="post-metadata">

**Author:** ![carltongibson](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/carltongibson/32/267_2.png) [@carltongibson](https://forum.djangoproject.com/u/carltongibson)\
**Post date:** [November 6, 2026, 10:37am UTC](https://forum.djangoproject.com/t/new-model-instances-with-a-primary-key-what-should-django-allow-36259/46262/7 "2026-11-06T10:37:54Z")

</div>

Super! I’m glad there was a good resolution. These issues are subtle, and can take a lot of looking into. 🎁
