Filter by file size in Django (FileField)
Asked Answered
H

1

5

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)
Hasan answered 23/10, 2018 at 16:13 Comment(0)
O
8

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.

Owner answered 23/10, 2018 at 16:21 Comment(1)
Thank you! I'll save file size as another field in model.Hasan

© 2022 - 2024 — McMap. All rights reserved.