pythonpython-3.xdjangodjango-models

how to update / replace a file in a Django FileField()


I have a Django model that holds a file like so:

class Excel(models.Model):
    the_generated_file = models.FileField()

I know want to access this file with an updated version of the file. If this was a int, foat or Json field etc I could use something like:

File_to_update = Excel.objects.all()
File_to_update.update(the_generated_file = my_new_excel_previously_defined)

But for some reason as it is of type FiledField() there is no update operation. How can I replace the old file with a new file?


Solution

  • Okay, you should try

    file_to_update = Excel.objects.all()[0]
    file_to_update.the_generated_file = 'foo'
    file_to_update.save()
    

    You have to call .save() to ensure the new file is uploaded to your file storage. Form the docs:

    The file is saved as part of saving the model in the database, so the actual file name used on disk cannot be relied on until after the model has been saved.

    Docs references: