Skip to content

Instantly share code, notes, and snippets.

@ViktorovEugene
Last active February 1, 2017 15:28
Show Gist options
  • Save ViktorovEugene/52c66ea1799c50056cff325cba345102 to your computer and use it in GitHub Desktop.
Save ViktorovEugene/52c66ea1799c50056cff325cba345102 to your computer and use it in GitHub Desktop.
The utility tool for copying all image files attached to the `django.db.models.ImageField` of the given model for the queryset.
from shutil import copy2
from django.conf import settings
from django.db import models
import os
def get_image_paths(queryset):
img_fields = [f.name for f in queryset.model._meta.fields if
isinstance(f, models.ImageField)]
images = []
for item in queryset:
for field in img_fields:
images.append(
getattr(item, field).path
)
return images
def copy_images(src_path_list, dst_path, common_path=None):
if not common_path:
common_path = os.path.commonpath(src_path_list + [os.getcwd()])
if not common_path[-1] == os.sep:
common_path += os.sep
assert os.path.isdir(common_path)
for img_path in src_path_list:
img_dst = os.path.join(dst_path, img_path.rpartition(common_path)[-1])
os.makedirs(os.path.dirname(img_dst), exist_ok=True)
print(copy2(img_path, img_dst))
def copy_images_of_queryset(queryset, dst_path):
image_paths = get_image_paths(queryset)
common_path = os.path.abspath(settings.MEDIA_ROOT)
copy_images(image_paths, dst_path, common_path=common_path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment