django - 对 Django 的 ImageField 宽度和高度感到困惑

标签 django image

我添加了图片 widthheight字段到基于 ImageField 的模型:

class Photo(models.Model):
    height = models.IntegerField()
    width = models.IntegerField()
    image = models.ImageField(
        upload_to=settings.PHOTO_UPLOAD_TO,
        height_field='height',
        width_field='width'
    )

当我这样做时 manage.py makemigrations ,我被要求为现有行提供默认值。我已经在数据库中有很多照片(它是一个正在运行的站点),因此我选择添加 default=0widthheight .
    height = models.IntegerField(default=0)
    width = models.IntegerField(default=0)

现在,对于所有现有照片,两列都按预期填充了零。然而我没想到的是 Photo.objects.all()[0].width.height现在返回正确的非零值。为什么?我在 documentation 中找不到有关此类行为的任何信息.

最佳答案

似乎魔术正在 Django 的 ImageField.update_dimension_fields 中执行方法。代码中的注释说:

Update field's width and height fields, if defined.

This method is hooked up to model's post_init signal to update dimensions after instantiating a model instance. However, dimensions won't be updated if the dimensions fields are already populated. This avoids unnecessary recalculation when loading an object from the database.

Dimensions can be forced to update with force=True, which is how ImageFileDescriptor.__set__ calls this method.



所以在实例化模型时,update_dimension_fields从图像文件中读取尺寸并将其存储在实例上。这将在现场环境中产生一些影响。

保存所有图像会将尺寸存储在数据库中:
In [1]: for p in Photo.objects.all():
   ...:     p.save()

关于django - 对 Django 的 ImageField 宽度和高度感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43300031/

相关文章:

css - 如何给图片添加文字装饰?

ios - 设置绘制到图像时文本的描边宽度

Django ListView如何获得digg风格的分页

angular - 在使用 ngx-img-cropper 的 Angular 中,如何获取裁剪后的 jpg 或 png 文件,而不是 base64 图像

python - Django - 方法签名与类中基方法的签名不匹配

django - 将文件上传到django中的私有(private)位置

java - 如何将图片切割成等份?

javascript - 在 html Canvas 上使用图像作为按钮

javascript - 用于用户登录/注册的 Django 模式 - 表单渲染问题

django - 使用带外键的Q对象定义django查询集