Skip to content

Commit

Permalink
Exclude empty objects during picture migration (#120)
Browse files Browse the repository at this point in the history
  • Loading branch information
amureki authored Aug 15, 2023
1 parent d50696d commit 85b61d4
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
5 changes: 4 additions & 1 deletion pictures/migrations.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from django.db import models
from django.db.migrations import AlterField
from django.db.models import Q

from pictures.models import PictureField, PictureFieldFile

Expand Down Expand Up @@ -46,7 +47,9 @@ def alter_picture_field(
self.update_pictures(from_field, to_model)

def update_pictures(self, from_field: PictureField, to_model: Type[models.Model]):
for obj in to_model._default_manager.all().iterator():
for obj in to_model._default_manager.exclude(
Q(**{self.name: ""}) | Q(**{self.name: None})
).iterator():
field_file = getattr(obj, self.name)
field_file.update_all(
from_aspect_ratios=PictureFieldFile.get_picture_files(
Expand Down
23 changes: 23 additions & 0 deletions tests/test_migrations.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,29 @@ class Meta:
)
assert path.exists()

@pytest.mark.django_db
def test_update_pictures__without_picture(self, request, stub_worker):
class ToModel(models.Model):
name = models.CharField(max_length=100)
picture = PictureField(
upload_to="testapp/profile/", aspect_ratios=[None, "21/9"], blank=True
)

class Meta:
app_label = request.node.name
db_table = "testapp_profile"

luke = Profile.objects.create(name="Luke")
stub_worker.join()
migration = migrations.AlterPictureField("profile", "picture", PictureField())
from_field = Profile._meta.get_field("picture")

migration.update_pictures(from_field, ToModel)
stub_worker.join()
luke.refresh_from_db()

assert not luke.picture

@pytest.mark.django_db
def test_from_picture_field(self, stub_worker, image_upload_file):
luke = Profile.objects.create(name="Luke", picture=image_upload_file)
Expand Down

0 comments on commit 85b61d4

Please sign in to comment.