Tuesday, August 25, 2015

Re: Migrations and FileField storage

Hi Nico,

I had the same problem when I was using this storage object:

photoStorage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'photos/original'), base_url='/photos/original')

class Photo(models.Model):
image = models.ImageField(storage=photoStorage)

The "location" argument ends up being serialized, which makes the migrations dependent on MEDIA_ROOT. To fix the problem I wrote my own subclass of FileSystemStorage:

@deconstructible
class PhotoFileSystemStorage(FileSystemStorage):
def __init__(self, photoPath):
self.photoPath = photoPath
super(PhotoFileSystemStorage,self).__init__(location=os.path.join(settings.MEDIA_ROOT, self.photoPath), base_url=self.photoPath)

def __eq__(self, other):
       return self.photoPath == other.photoPath

photoStorage = PhotoFileSystemStorage('photos/original')

When an instance of PhotoFileSystemStorage is serialized it just writes out self.photoPath, which does not depend on MEDIA_ROOT. After implementing this, the migration looks like this:

class Migration(migrations.Migration):

    dependencies = [
        ...
    ]

    operations = [
        migrations.AlterField(
            model_name='photo',
            name='image',
            field=models.ImageField(storage=myapp.models.PhotoFileSystemStorage(b'photos/original')),
        ),
    ]

You can see it does not depend on MEDIA_ROOT and won't be different if you move the project around or deploy it.

The django docs on this are here: https://docs.djangoproject.com/en/1.8/topics/migrations/

Hope this helps.


Steve


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/b1972234-7ef7-48f6-8dee-afcfacf7fafb%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment