AnDrOiD AnDrOiD - 1 month ago 7
Python Question

Storing Multiple Files for Each Instance of A Model

I have a simple model of a

Student
and I'd like to be able to store an unknown amount of documents for each student. I thought about adding a
FileField
to the model but then I'd have to add a
FileField
for each document.

My question is what is the most efficient way to store documents for each student?




Edit:

I thought about using another model with a OneToMany field but then I got stuck because I also need to display all the associated files with a specific
Student
in his admin change form.

Answer

As Mounir mentioned in the comments, I had to make another model (let's call it "Document") to contain the file with FileField and a ForeignKey to the Student model.

After that I had to assign that Document model to a InlineModelAdmin (I used TabularInline):

class DocumentInline(admin.TabularInline):
    model = Document

And then just add it to the main ModelAdmin through inlines:

class StudentAdmin(admin.ModelAdmin):
    ...
    inlines = [
        DocumentInline,
    ]
Comments