ncopiy
ncopiy

Reputation: 1604

Filter by file size in Django (FileField)

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)

Upvotes: 5

Views: 1291

Answers (1)

dirkgroten
dirkgroten

Reputation: 20692

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.

Upvotes: 8

Related Questions