我添加了图片 width
和 height
字段到基于 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=0
至 width
和 height
. 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 howImageFileDescriptor.__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/