Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed 30138 -- Allow QuerySet.bulk_create() to set pk of created objects when ignore_conflicts=True #10998

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 2 additions & 1 deletion django/db/backends/base/operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,8 @@ def fetch_returned_insert_id(self, cursor):
statement into a table that has an auto-incrementing ID, return the
newly created ID.
"""
return cursor.fetchone()[0]
results = cursor.fetchone()
return results[0] if isinstance(results, tuple) else None

def field_cast_sql(self, db_type, internal_type):
"""
Expand Down
2 changes: 1 addition & 1 deletion django/db/models/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -1187,7 +1187,7 @@ def _batched_insert(self, objs, fields, batch_size, ignore_conflicts=False):
inserted_ids = []
bulk_return = connections[self.db].features.can_return_rows_from_bulk_insert
for item in [objs[i:i + batch_size] for i in range(0, len(objs), batch_size)]:
if bulk_return and not ignore_conflicts:
if bulk_return:
inserted_id = self._insert(
item, fields=fields, using=self.db, return_id=True,
ignore_conflicts=ignore_conflicts,
Expand Down
33 changes: 33 additions & 0 deletions tests/postgres_tests/test_bulk_create.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
from datetime import date
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

postgres_tests is for testing django.contrib.postgres. Use tests/bulk_create and @skipUnlessDBFeature('can_return_rows_from_bulk_insert').

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, I didn't know that. I'll use tests/bulk_create instead.


from . import PostgreSQLTestCase
from .models import (
HStoreModel, IntegerArrayModel, JSONModel, NestedIntegerArrayModel,
NullableIntegerArrayModel, OtherTypesArrayModel, RangesModel,
)

try:
from psycopg2.extras import NumericRange, DateRange
except ImportError:
pass # psycopg2 isn't installed.


class BulkCreateTests(PostgreSQLTestCase):
def test_bulk_create_to_set_pk_when_ignore_conflicts(self):
test_data = [
(IntegerArrayModel, 'field', [], [1, 2, 3]),
(NullableIntegerArrayModel, 'field', [1, 2, 3], None),
(JSONModel, 'field', {'a': 'b'}, {'c': 'd'}),
(NestedIntegerArrayModel, 'field', [], [[1, 2, 3]]),
(HStoreModel, 'field', {}, {1: 2}),
(RangesModel, 'ints', None, NumericRange(lower=1, upper=10)),
(RangesModel, 'dates', None, DateRange(lower=date.today(), upper=date.today())),
(OtherTypesArrayModel, 'ips', [], ['1.2.3.4']),
(OtherTypesArrayModel, 'json', [], [{'a': 'b'}])
]
for Model, field, initial, new in test_data:
with self.subTest(model=Model, field=field):
objs = (Model(**{field: initial}) for _ in range(20))
instances = Model.objects.bulk_create(objs, ignore_conflicts=True)
for instance in instances:
self.assertIsNotNone(instance.pk)