Django has a built in
ImageField - it is great & makes dealing with images very easy. However, out of the box, you can't query the database for images of a certain dimension (width or height). For example, you can't find all the large images you are storing.
The solution is hiding in plain sight in the Django docs.
ImageField accepts two arguments:
width_field. Using these are pretty easy:
from django.db import models class Person(models.Model): avatar = models.ImageField( blank=True, null=True, height_field="avatar_height", width_field="avatar_width", ) avatar_height = models.IntegerField(blank=True, null=True) avatar_width = models.IntegerField(blank=True, null=True)
Every time we save an image to the
avatar field, Django will automatically update the
avatar_width fields with the new image dimensions.
This means we now have an entry in the database that we can query! If we wanted to find all the images with at least one large dimension, we can do something like:
from django.db.models import Q big_dim = 500; big_images = Person.objects.filter( Q(avatar_height__gt=big_dim) | Q(avatar_width__gt=big_dim) )
Couple of final notes:
- The fields are only updated on "save", so if you are adding this to an existing model, you may want to loop through each instance & call
save()so that the fields are populated
- Normal usage of
person.avatar.heightwould load the whole image into memory in order to figure out how big it is. This can be slow if you are using a remote storage such as S3 or Digital Ocean Spaces. But using
person.avatar_heightskips all that. This can lead to a big performance increase if you need to know the size of your images but don't need to operate on the image itself.