【问题标题】:Django: changing model's schema (replace CharField with ImageField)Django:更改模型的架构(将 CharField 替换为 ImageField)
【发布时间】:2012-07-30 07:44:46
【问题描述】:

我基于 Django 框架修改项目。我有表格来添加一个项目。商品有封面(图片)。此商品商店封面的 url 的当前模型版本如下:

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.CharField(max_length = 255, null = True, default = None)
    ...

重要注意,有些图像存储在其他服务器上(不同的文件托管)。

我想用 ImageField 替换 CharField。但是现有的项目呢?我想更改模型的架构并保存所有以前添加的图像。我怎样才能实现这个目标?

也许这种修改的一些原因可能会有所帮助。主要原因是为用户提供从他们的计算机上传图片的能力(不仅仅是插入原来的 url)。

TIA!

【问题讨论】:

  • 您实际上不需要更改架构。 CharFieldImageField 都作为 VARCHAR 类型存储在数据库中。唯一真正的区别在于 Python 方面。
  • 我考虑了一下。最可取的方法是在表单模板中使用另一个小部件。我的意思是 - 在模型中我有 CharField,但在表单中我使用 和“文件”类型。但是当我尝试在表单的课堂上这样做时,我会遇到一些错误。也许我应该修改表单模板 - 添加必要类型的输入?
  • 不,您需要在您的模型上使用实际的ImageField。我的观点是,将字段从 CharField 更改为 ImageField 不需要更改架构。

标签: django django-models


【解决方案1】:

如果cover_url 可以有现有源 - 您必须有自定义存储,它可以处理外部源。

这是来自django documentationImageField 的自定义存储使用示例:

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)

让我们跳出来,我们会得到这样的代码:

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)

它有很大的改进空间 - 这里只显示想法。

【讨论】:

    猜你喜欢
    • 2016-06-30
    • 1970-01-01
    • 2021-04-20
    • 1970-01-01
    • 1970-01-01
    • 2020-11-19
    • 2020-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多