ModelState should be inspected to determine whether an object is being created or updated #10279

Closed
opened 2025-12-29 21:29:22 +01:00 by adam · 0 comments
Owner

Originally created by @jeremystretch on GitHub (Sep 23, 2024).

Originally assigned to: @jeremystretch on GitHub.

Proposed Changes

Anywhere it's necessary to determine whether an object is being created or updated (e.g. inside clean()), we should inspect the instance's _state attribute, which is a ModelState object. The _adding boolean of this object indicates whether the instance is being added to the database or updated.

Justification

In many places around the application, we use if self.pk as a shorthand for determining whether an object has already been created in the database. (If not, its primary key will not yet be set.) However, this assumes that the primary key can never be known in advance, which may not necessarily be true. For instance, the netbox-branching plugin copies predetermined primary keys when creating an object.

Originally created by @jeremystretch on GitHub (Sep 23, 2024). Originally assigned to: @jeremystretch on GitHub. ### Proposed Changes Anywhere it's necessary to determine whether an object is being created or updated (e.g. inside `clean()`), we should inspect the instance's [`_state` attribute](https://docs.djangoproject.com/en/5.1/ref/models/instances/#django.db.models.Model._state), which is a ModelState object. The `_adding` boolean of this object indicates whether the instance is being added to the database or updated. ### Justification In many places around the application, we use `if self.pk` as a shorthand for determining whether an object has already been created in the database. (If not, its primary key will not yet be set.) However, this assumes that the primary key can never be known in advance, which may not necessarily be true. For instance, the [netbox-branching plugin](https://github.com/netboxlabs/netbox-branching) copies predetermined primary keys when creating an object.
adam added the status: acceptedtype: housekeeping labels 2025-12-29 21:29:22 +01:00
adam closed this issue 2025-12-29 21:29:22 +01:00
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: starred/netbox#10279