diff options
| author | Simon Charette <charette.s@gmail.com> | 2025-01-11 01:08:35 -0500 |
|---|---|---|
| committer | Sarah Boyce <42296566+sarahboyce@users.noreply.github.com> | 2025-01-13 11:13:29 +0100 |
| commit | 9e552015556661d183a999078a9e846200ef6765 (patch) | |
| tree | 434cbeb5be28ffb5e89c51d629377dfc28932105 /tests/model_fields | |
| parent | 20eb4bca7de945d8858d1354a8c624406c0b90bd (diff) | |
Fixed #36086 -- Fixed crash when using GeneratedField with non-AutoField pk.
The previous logic was systematically attempting to retrieve last_insert_id
even for models without an AutoField primary key when they had a GeneratedField
on backends that can't return columns from INSERT.
The issue affected MySQL, SQLite < 3.35, and Oracle when the use_returning_into
option was disabled and could result in either crashes when the non-auto
primary key wasn't an IntegerField subclass or silent misassignment of bogus
insert ids (0 or the previous auto primary key insert value) to the first
defined generated field value.
Diffstat (limited to 'tests/model_fields')
| -rw-r--r-- | tests/model_fields/models.py | 13 | ||||
| -rw-r--r-- | tests/model_fields/test_generatedfield.py | 7 |
2 files changed, 20 insertions, 0 deletions
diff --git a/tests/model_fields/models.py b/tests/model_fields/models.py index 599efafe7e..fdea06b23d 100644 --- a/tests/model_fields/models.py +++ b/tests/model_fields/models.py @@ -527,6 +527,19 @@ class GeneratedModel(models.Model): required_db_features = {"supports_stored_generated_columns"} +class GeneratedModelNonAutoPk(models.Model): + id = models.IntegerField(primary_key=True) + a = models.IntegerField() + b = models.GeneratedField( + expression=F("a"), + output_field=models.IntegerField(), + db_persist=True, + ) + + class Meta: + required_db_features = {"supports_stored_generated_columns"} + + class GeneratedModelVirtual(models.Model): a = models.IntegerField() b = models.IntegerField() diff --git a/tests/model_fields/test_generatedfield.py b/tests/model_fields/test_generatedfield.py index c185e19d8b..e00a665ec8 100644 --- a/tests/model_fields/test_generatedfield.py +++ b/tests/model_fields/test_generatedfield.py @@ -22,6 +22,7 @@ from .models import ( GeneratedModelCheckConstraint, GeneratedModelCheckConstraintVirtual, GeneratedModelFieldWithConverters, + GeneratedModelNonAutoPk, GeneratedModelNull, GeneratedModelNullVirtual, GeneratedModelOutputFieldDbCollation, @@ -356,6 +357,12 @@ class StoredGeneratedFieldTests(GeneratedFieldTestMixin, TestCase): obj = self._refresh_if_needed(obj) self.assertEqual(obj.field, obj.field_copy) + def test_create_with_non_auto_pk(self): + obj = GeneratedModelNonAutoPk.objects.create(id=1, a=2) + self.assertEqual(obj.id, 1) + self.assertEqual(obj.a, 2) + self.assertEqual(obj.b, 2) + @skipUnlessDBFeature("supports_virtual_generated_columns") class VirtualGeneratedFieldTests(GeneratedFieldTestMixin, TestCase): |
