简体   繁体   English

CharField 文件名到 Django 中的 ImageFields

[英]CharField filenames into ImageFields in Django

I have a model:我有一个 model:

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

And a corresponding MySQL table, filled with filenames (copied from an existing table).以及相应的 MySQL 表,其中填充了文件名(从现有表中复制)。

In the future I may want to upload new photos to the model via admin.将来我可能想通过管理员将新照片上传到 model。 Is it possible to evolve the current model into something with ImageFields and integrate my legacy data?是否可以将当前的 model 演变成具有 ImageFields 的东西并集成我的旧数据?

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.有可能,假设 model 中的当前filename段包含实际文件的完整路径,您可以向 model 添加一个新字段 (ImageField) 并使用 South 迁移它,然后编写一个脚本来更新您的数据。

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.然后通过 South 删除旧的filename段。 Take a look at Django's FileField first for more information, since ImageField essentially inherits all of the former's attribute and methods.请先查看 Django 的FileField以获得更多信息,因为ImageField本质上继承了前者的所有属性和方法。 (see https://docs.djangoproject.com/en/1.3/ref/models/fields/#django.db.models.FileField ) (见https://docs.djangoproject.com/en/1.3/ref/models/fields/#django.db.models.FileField

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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