'Separating files based on file extension?

I want to separate the files in my models based on extension type. Right now I am able to print all the files but now I want to separate them based on extension and apply separate functions based on the extensions.

The code in my models.py

class File(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    doc = models.FileField(upload_to='files/docs/', validators=[FileExtensionValidator(allowed_extensions=['pdf','docx'])])`

and my code in view.py

def file_p():

    for file in File.objects.all():
        print(file.doc)

I am getting an output something like this:

files/docs/12.6.1-packet-tracer---troubleshooting-challenge---document-the-network_1s00TUA.docx
files/docs/12.6.1-packet-tracer---troubleshooting-challenge---document-the-network_z9b2tyh.pdf

How can I separate them based on the extension so that I can apply further functions based on the file type?



Solution 1:[1]

You can make this using custom Model functions. models.py

class File(modles.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    doc = models.FileField(upload_to='files/docs/', validators=[FileExtensionValidator(allowed_extensions=['pdf','docx'])])
 
    def doc_pdf(self):
        name, extension = os.path.splitext(self.doc.name)
        if 'pdf' in extension:
            return self.doc
    def doc_docx(self):
        name, extension = os.path.splitext(self.doc.name)
        if 'docx' in extension:
            return self.doc

views.py

def file_p():
    for file in File.objects.all():
        #get pdf files
        print(file.doc_pdf)
        #get docx files
        print(file.doc_docx)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1