Source

gnocchi-catalogue / catalogue / management / commands / sync_product_images.py

Full commit
from django.core.management.base import NoArgsCommand
from gnocchi_catalogue.models import Product, ProductImage
from django.conf import settings
from glob import glob
import os.path

class Command(NoArgsCommand):
    help = "Ensure an Image entry exists for all files in images/ directory"

    def handle_noargs(self, **options ):
        root_path = os.path.join( settings.MEDIA_ROOT, 'images/products/' )

        pfx = len(settings.MEDIA_ROOT)
        for product in Product.objects.all():
            print "Product: %s" % product
            prod_path = os.path.join( root_path, str(product.id), '*' )
            print "Searching: %s" % prod_path
            for filename in glob( prod_path ):
                filename = filename[pfx:] # strip media path
                print "Found: %s" % filename
                if not product.productimage_set.filter( image=filename ).count():
                    print "[%s] Adding Image: %s" % ( product, filename, ),
                    try:
                        ProductImage.objects.create(
                            product=product,
                            image=filename,
                            order=1
                        )
                    except:
                        print " Failed!"
                    else:
                        print " Done!"
        print "Done."