简体   繁体   中英

CharField filenames into ImageFields in Django

I have a model:

class Photo(models.Model):
    filename = models.CharField(max_length=240)

And a corresponding MySQL table, filled with filenames (copied from an existing table).

In the future I may want to upload new photos to the model via admin. Is it possible to evolve the current model into something with ImageFields and integrate my legacy data?

It is possible, assuming the current filename field in your model contains the full path to the actual file, you can add a new field (ImageField) to your model and migrate it using South, then write a script to update your data.

A skeleton example,

from django.core.files import File

# assuming your updated model looks like:
# class Photo(models.Model):
#     filename = models.CharField(max_length=240)
#     image = models.ImageField(max_length=240)

photos = Photo.objects.all()
for p in photos:
    f = open(p.filename)
    myimage = File(f)
    p.image.save(image_name, myimage) # name, content

And then remove the old filename field via South. Take a look at Django's FileField first for more information, since ImageField essentially inherits all of the former's attribute and methods. (see https://docs.djangoproject.com/en/1.3/ref/models/fields/#django.db.models.FileField )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM