Skip to content

Commit 85b61d4

Browse files
authored
Exclude empty objects during picture migration (#120)
1 parent d50696d commit 85b61d4

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

pictures/migrations.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from django.db import models
44
from django.db.migrations import AlterField
5+
from django.db.models import Q
56

67
from pictures.models import PictureField, PictureFieldFile
78

@@ -46,7 +47,9 @@ def alter_picture_field(
4647
self.update_pictures(from_field, to_model)
4748

4849
def update_pictures(self, from_field: PictureField, to_model: Type[models.Model]):
49-
for obj in to_model._default_manager.all().iterator():
50+
for obj in to_model._default_manager.exclude(
51+
Q(**{self.name: ""}) | Q(**{self.name: None})
52+
).iterator():
5053
field_file = getattr(obj, self.name)
5154
field_file.update_all(
5255
from_aspect_ratios=PictureFieldFile.get_picture_files(

tests/test_migrations.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,29 @@ class Meta:
144144
)
145145
assert path.exists()
146146

147+
@pytest.mark.django_db
148+
def test_update_pictures__without_picture(self, request, stub_worker):
149+
class ToModel(models.Model):
150+
name = models.CharField(max_length=100)
151+
picture = PictureField(
152+
upload_to="testapp/profile/", aspect_ratios=[None, "21/9"], blank=True
153+
)
154+
155+
class Meta:
156+
app_label = request.node.name
157+
db_table = "testapp_profile"
158+
159+
luke = Profile.objects.create(name="Luke")
160+
stub_worker.join()
161+
migration = migrations.AlterPictureField("profile", "picture", PictureField())
162+
from_field = Profile._meta.get_field("picture")
163+
164+
migration.update_pictures(from_field, ToModel)
165+
stub_worker.join()
166+
luke.refresh_from_db()
167+
168+
assert not luke.picture
169+
147170
@pytest.mark.django_db
148171
def test_from_picture_field(self, stub_worker, image_upload_file):
149172
luke = Profile.objects.create(name="Luke", picture=image_upload_file)

0 commit comments

Comments
 (0)