N
N
NyxDeveloper2021-01-27 14:12:06
Django
NyxDeveloper, 2021-01-27 14:12:06

How to assign a FileField to a file knowing only the path to it?

It is necessary to copy files from the old database, but since the database does not specifically store files, but only the paths to them, when creating a new object, you need to somehow get the file along this path and assign it to the model field, and then django, sort of like and he will understand what needs to be done. I have never encountered this, the docks say about assignment from forms, I tried to assign a path in the field - it didn’t help, I opened it through with rb - it doesn’t help either. I'm probably completely layman in this matter, but tell someone how you can implement such an assignment?
Now I'm trying to do this:

def load_d_docs(cursor):
    cursor.execute('SELECT * FROM d_docs')
    for row in cursor:
        obj = Doc()
        obj.id = row[0]
        if row[2] is not None:
            with open(row[2], 'rb') as file:
                obj.file = file.read()
        if row[4] is not None:
            obj.idProj = Project.objects.get(id=row[4])
        if row[5] is not None:
            obj.description = row[4]
        if row[8] is not None:
            obj.dateUpload = row[8]
        obj.save()

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question