Filter by file size in Django (FileField)

Viewed 844

I have an a model:

class MyModel(models.Model):
    file = models.FileField(verbose_name='File', upload_to="files/")

I can get file size in bytes:

size = my_model_instance.file.size

How to filter by file size in Django? Something like that:

MyModel.object.filter(file.size__lt=128)
1 Answers

You can't. model_instance.file.size actually opens the associated file and fetches the size from disk. The only thing saved in the database is the path to the file.

If you want to be able to filter by file size, you'd have to save the size in the database as an extra field of your model. You could populate that field automatically when saving the model.

Related