width_field
和 height_field
。height
和 width
信息from django.db import models
class Photo(models.Model):
image = models.ImageField(
blank=True,
null=True,
height_field="height",
width_field="width",
)
height = models.PositiveIntegerField(default=0)
width = models.PositiveIntegerField(default=0)
from django.db.models import Q
big_dim = 1024;
big_images = Photo.objects.filter(
Q(height=big_dim) | Q(width=big_dim)
)
width
和 height
信息每次查询都会把图片数据读到内存。width_field
和 height_field
pre_save
在存储图片前设置图片大小from django.db import models
from django.db.models.signals import pre_save
from django.dispatch import receiver
class Photo(models.Model):
image = models.ImageField(
blank=True,
null=True,
)
height = models.PositiveIntegerField(blank=True, null=True)
width = models.PositiveIntegerField(blank=True, null=True)
@receiver(pre_save, sender=Photo)
def set_photo_dim(sender, instance: Photo, raw, **kwargs):
if isinstance(instance, sender):
setattr(instance, "width", instance.file.width)
setattr(instance, "height", instance.file.height)