[Answered ]-Django: changing model's schema (replace CharField with ImageField)

2👍

If cover_url can have existing source – you must have custom storage, that can handle external sources.

Here is example of custom storage usage for ImageField from django documentation:

from django.db import models
from django.core.files.storage import FileSystemStorage

fs = FileSystemStorage(location='/media/photos')

class Car(models.Model):
    ...
    photo = models.ImageField(storage=fs)

Let’s jump out of it and we will get code like this:

from django.db import models
from django.core.files.storage import FileSystemStorage

def is_url(name):
    return 'http' in name

class MyStorage(FileSystemStorage):
    #We should override _save method, instead of save. 
    def _save(self, name, content=None):
        if content is None and is_url(name):
            return name
        super(MyStorage, self)._save(name, content)

fs = MyStorage()

class Item(models.Model):
    title = models.CharField(max_length = 255, db_index = True)
    slug = models.CharField(max_length = 80, db_index = True)
    categories = models.ManyToManyField(Category)
    cover_url = models.ImageField(storage=fs)

It has big room for improvements – here is shown only idea.

Leave a comment