为每个模型实例存储多个文件(Storing Multiple Files for Each Instance of A Model)

编程入门 行业动态 更新时间:2024-10-26 00:30:11
为每个模型实例存储多个文件(Storing Multiple Files for Each Instance of A Model)

我有一个简单的Student模型,我希望能够为每个学生存储未知数量的文档。 我想过为模型添加一个FileField ,但是我必须为每个文档添加一个FileField 。

我的问题是为每个学生存储文档的最有效方式是什么?

编辑:

我想过使用OneToMany字段的另一个模型,但后来因为我还需要在他的管理更改表单中显示与特定Student相关的所有文件。

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.

最满意答案

正如Mounir在评论中提到的那样,我必须创建另一个模型(让我们称之为“ Document ”)来将包含FileField和ForeignKey的文件包含到Student模型中。

之后我不得不将该Document模型分配给InlineModelAdmin (我使用了TabularInline ):

class DocumentInline(admin.TabularInline): model = Document

然后只需通过内inlines将其添加到主ModelAdmin :

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

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, ]

更多推荐

本文发布于:2023-08-04 14:13:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1416441.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   实例   模型   文件   Storing

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!