From 841cb45847f9a96c108e038300006b4c45aef12a Mon Sep 17 00:00:00 2001 From: Kenneth Date: Tue, 12 Jul 2016 14:32:55 -0700 Subject: [PATCH] Fixed #26884 -- Evaluated callables in QuerySet.update_or_create()'s defaults when updating. --- django/db/models/query.py | 2 +- tests/get_or_create/tests.py | 14 +++++++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/django/db/models/query.py b/django/db/models/query.py index 4085e618cf..6e9741c9fe 100644 --- a/django/db/models/query.py +++ b/django/db/models/query.py @@ -489,7 +489,7 @@ class QuerySet(object): if created: return obj, created for k, v in six.iteritems(defaults): - setattr(obj, k, v) + setattr(obj, k, v() if callable(v) else v) obj.save(using=self.db) return obj, False diff --git a/tests/get_or_create/tests.py b/tests/get_or_create/tests.py index 567ad880fa..0cbb9a1fff 100644 --- a/tests/get_or_create/tests.py +++ b/tests/get_or_create/tests.py @@ -404,9 +404,21 @@ class UpdateOrCreateTests(TestCase): self.assertFalse(created) self.assertEqual(obj.defaults, 'another testing') - def test_update_callable_default(self): + def test_create_callable_default(self): obj, created = Person.objects.update_or_create( first_name='George', last_name='Harrison', defaults={'birthday': lambda: date(1943, 2, 25)}, ) + self.assertIs(created, True) self.assertEqual(obj.birthday, date(1943, 2, 25)) + + def test_update_callable_default(self): + Person.objects.update_or_create( + first_name='George', last_name='Harrison', birthday=date(1942, 2, 25), + ) + obj, created = Person.objects.update_or_create( + first_name='George', + defaults={'last_name': lambda: 'NotHarrison'}, + ) + self.assertIs(created, False) + self.assertEqual(obj.last_name, 'NotHarrison')