Fix IntegrityError when cloning objects with pk=None (#664) (#707)

* Fix IntegrityError when cloning objects with pk=None

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
This commit is contained in:
Jakub Ječmínek 2025-03-19 14:54:03 +01:00 committed by GitHub
parent 939dd9b298
commit 4c1d573981
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 12 additions and 1 deletions

View file

@ -20,6 +20,7 @@ via `AUDITLOG_MASK_TRACKING_FIELDS` setting. ([#702](https://github.com/jazzband
- Fixed a problem when setting `Value(None)` in `JSONField` ([#646](https://github.com/jazzband/django-auditlog/pull/646))
- Fixed a problem when setting `django.db.models.functions.Now()` in `DateTimeField` ([#635](https://github.com/jazzband/django-auditlog/pull/635))
- Use the [default manager](https://docs.djangoproject.com/en/5.1/topics/db/managers/#default-managers) instead of `objects` to support custom model managers. ([#705](https://github.com/jazzband/django-auditlog/pull/705))
- Fixed crashes when cloning objects with `pk=None` ([#707](https://github.com/jazzband/django-auditlog/pull/707))
## 3.0.0 (2024-04-12)

View file

@ -53,7 +53,7 @@ def log_update(sender, instance, **kwargs):
Direct use is discouraged, connect your model through :py:func:`auditlog.registry.register` instead.
"""
if not instance._state.adding:
if not instance._state.adding and instance.pk is not None:
update_fields = kwargs.get("update_fields", None)
old = sender._default_manager.filter(pk=instance.pk).first()
_create_log_entry(

View file

@ -235,6 +235,13 @@ class SimpleModelTest(TestCase):
history = self.obj.history.filter(timestamp=timestamp, changes="foo bar")
self.assertTrue(history.exists())
def test_create_duplicate_with_pk_none(self):
initial_entries_count = LogEntry.objects.count()
obj = self.obj
obj.pk = None
obj.save()
self.assertEqual(LogEntry.objects.count(), initial_entries_count + 1)
class NoActorMixin:
def check_create_log_entry(self, obj, log_entry):
@ -347,6 +354,9 @@ class ModelPrimaryKeyModelBase(SimpleModelTest):
self.key = super().make_object()
return ModelPrimaryKeyModel.objects.create(key=self.key, text="I am strange.")
def test_create_duplicate_with_pk_none(self):
pass
class ModelPrimaryKeyModelTest(NoActorMixin, ModelPrimaryKeyModelBase):
pass