diff --git a/stdimage/models.py b/stdimage/models.py index 6be0cf1..27e9023 100644 --- a/stdimage/models.py +++ b/stdimage/models.py @@ -240,7 +240,8 @@ def set_variations(self, instance=None, **kwargs): :param instance: FileField """ - if getattr(instance, self.name): + deferred_field = self.name in instance.get_deferred_fields() + if not deferred_field and getattr(instance, self.name): field = getattr(instance, self.name) if field._committed: for name, variation in list(self.variations.items()): diff --git a/tests/test_models.py b/tests/test_models.py index 6669e80..c7a7aa2 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -167,6 +167,20 @@ def test_custom_render_variations(self, db): assert instance.image.thumbnail.width == 100 assert instance.image.thumbnail.height == 100 + def test_defer(self, db, django_assert_num_queries): + """ + `set_variations` does not access a deferred field. + + Accessing a deferred field would cause Django to do + a second implicit database query. + """ + instance = ResizeModel.objects.create(image=self.fixtures['100.gif']) + with django_assert_num_queries(1): + deferred = ResizeModel.objects.only('pk').get(pk=instance.pk) + with django_assert_num_queries(1): + deferred.image + assert instance.image.thumbnail == deferred.image.thumbnail + class TestUtils(TestStdImage): """Tests Utils"""