Skip to content

Commit

Permalink
Fixed #35350 -- Fixed save() with pk set on models with GeneratedFields.
Browse files Browse the repository at this point in the history
Thanks Matt Hegarty for the report.

Regression in f333e35.
  • Loading branch information
sarahboyce committed Apr 9, 2024
1 parent ca5cd3e commit 1e35b07
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 5 deletions.
12 changes: 8 additions & 4 deletions django/db/models/base.py
Expand Up @@ -1063,12 +1063,16 @@ def _save_table(
for a single table.
"""
meta = cls._meta
non_pks = [f for f in meta.local_concrete_fields if not f.primary_key]
non_pks_non_generated = [
f
for f in meta.local_concrete_fields
if not f.primary_key and not f.generated
]

if update_fields:
non_pks = [
non_pks_non_generated = [
f
for f in non_pks
for f in non_pks_non_generated
if f.name in update_fields or f.attname in update_fields
]

Expand Down Expand Up @@ -1100,7 +1104,7 @@ def _save_table(
None,
(getattr(self, f.attname) if raw else f.pre_save(self, False)),
)
for f in non_pks
for f in non_pks_non_generated
]
forced_update = update_fields or force_update
updated = self._do_update(
Expand Down
4 changes: 3 additions & 1 deletion docs/releases/5.0.5.txt
Expand Up @@ -9,4 +9,6 @@ Django 5.0.5 fixes several bugs in 5.0.4.
Bugfixes
========

* ...
* Fixed a bug in Django 5.0 that caused a crash of ``Model.save()`` when
creating an instance of a model with a ``GeneratedField`` and
providing a primary key (:ticket:`35350`).
6 changes: 6 additions & 0 deletions tests/model_fields/test_generatedfield.py
Expand Up @@ -207,6 +207,12 @@ def test_save(self):
m.refresh_from_db()
self.assertEqual(m.field, 8)

def test_save_model_with_pk(self):
m = self.base_model(pk=1, a=1, b=2)
m.save()
m = self._refresh_if_needed(m)
self.assertEqual(m.field, 3)

def test_save_model_with_foreign_key(self):
fk_object = Foo.objects.create(a="abc", d=Decimal("12.34"))
m = self.base_model(a=1, b=2, fk=fk_object)
Expand Down

0 comments on commit 1e35b07

Please sign in to comment.