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

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:

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

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.

1 Like

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. 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 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.

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?

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.

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.)

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:

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.

Update:

Jacob has closed the ticket as invalid (ticket comment).

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.

2 Likes

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