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 funtions 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 extension so that i can apply further functions based on the file type.

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)

Back to Top