Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: FileField, missing content_type

If I read the docs correctly, then the FileField in Django does not know the content_type of the file: https://docs.djangoproject.com/en/2.1/ref/models/fields/

I would like to store files in a Django application, but I want to query the content_type.

Examples:

  • list all objects which have a file with content_type "application/pdf"
  • list all objects which have a file with content_type "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"

What is the most django-like way to handle this?

like image 287
guettli Avatar asked Apr 26 '26 21:04

guettli


1 Answers

Assuming you have a model as:

class Foo(models.Model):
    myfile = models.FileField(upload_to='files/')
    content_type = models.CharField(null=True, blank=True, max_length=100)

The field myfile is for storing files, and content_type is for storing the content-type of the corresponding file.

You could store the content_type type of a file by overriding the save() method of Foo model.

Django file field provides file.content_type attribute to handle the content_type type of the file. So change your model as:

class Foo(models.Model):
    myfile = models.FileField(upload_to='files/')
    content_type = models.CharField(null=True, blank=True, max_length=100)

    def save(self, *args, **kwargs):
        self.content_type = self.myfile.file.content_type
        super().save(*args, **kwargs)



Now, you could query the ORM by using filter() as:

Foo.objects.filter(content_type='application/pdf')
like image 197
JPG Avatar answered Apr 29 '26 10:04

JPG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!