diff --git a/django/db/models/query.py b/django/db/models/query.py index 1479bea47f..a8e1560853 100644 --- a/django/db/models/query.py +++ b/django/db/models/query.py @@ -490,7 +490,7 @@ class QuerySet: if not fields: raise ValueError('Field names must be given to bulk_update().') objs = tuple(objs) - if not all(obj.pk for obj in objs): + if any(obj.pk is None for obj in objs): raise ValueError('All bulk_update() objects must have a primary key set.') fields = [self.model._meta.get_field(name) for name in fields] if any(not f.concrete or f.many_to_many for f in fields): diff --git a/tests/queries/models.py b/tests/queries/models.py index ead8439118..af0af1d10c 100644 --- a/tests/queries/models.py +++ b/tests/queries/models.py @@ -591,6 +591,7 @@ class MyObject(models.Model): class Order(models.Model): id = models.IntegerField(primary_key=True) + name = models.CharField(max_length=12, null=True, default='') class Meta: ordering = ('pk',) diff --git a/tests/queries/test_bulk_update.py b/tests/queries/test_bulk_update.py index ab2bda289c..e2e9a6147a 100644 --- a/tests/queries/test_bulk_update.py +++ b/tests/queries/test_bulk_update.py @@ -7,7 +7,7 @@ from django.test import TestCase from .models import ( Article, CustomDbColumn, CustomPk, Detail, Individual, Member, Note, - Number, Paragraph, SpecialCategory, Tag, Valid, + Number, Order, Paragraph, SpecialCategory, Tag, Valid, ) @@ -167,6 +167,13 @@ class BulkUpdateTests(TestCase): [cat.extra for cat in custom_pks] ) + def test_falsey_pk_value(self): + order = Order.objects.create(pk=0, name='test') + order.name = 'updated' + Order.objects.bulk_update([order], ['name']) + order.refresh_from_db() + self.assertEqual(order.name, 'updated') + def test_inherited_fields(self): special_categories = [ SpecialCategory.objects.create(name=str(i), special_name=str(i))