Python 如何在django中的模型中添加动态字段?
我正在使用django创建一个应用程序下载站点。我尝试编写一个模型,管理员可以在管理员页面中动态添加不同的下载内容。例如,我有一个名为foobar的软件,它有3个不同的版本:1.1、1.2、1.3。我想用户可以管理通过使用添加按钮添加与下载版本的下载链接模型。但我不知道在django怎么做 将您的模型设置为具有主模型和具有主模型外键的辅助模型:Python 如何在django中的模型中添加动态字段?,python,database,django,Python,Database,Django,我正在使用django创建一个应用程序下载站点。我尝试编写一个模型,管理员可以在管理员页面中动态添加不同的下载内容。例如,我有一个名为foobar的软件,它有3个不同的版本:1.1、1.2、1.3。我想用户可以管理通过使用添加按钮添加与下载版本的下载链接模型。但我不知道在django怎么做 将您的模型设置为具有主模型和具有主模型外键的辅助模型: class DownloadItem(models.Model): name = models.CharField( etc etc) .
class DownloadItem(models.Model):
name = models.CharField( etc etc)
... other attributes here ...
class DownloadItemFile(models.Model):
parent = models.ForeignKey('DownloadItem', related_name="versions")
version = models.CharField( etc etc)
file = models.FileField(upload='path/to/uploaddir/')
然后,当您拥有DownloadItem模型的实例时,您可以使用以下工具获得各种文件版本:
mydownloaditem.versions.all()
为了能够通过管理员添加文件,您需要使用内联。在有关应用程序的admin.py中,您需要添加以下内容:
class DownloadItemFileInline(admin.TabularInline):
model = DownloadItemFile
class DownloadItemAdminOptions(admin.ModelAdmin):
inlines = [ DownloadItemFileInline, ]
...other admin options here...
admin.site.register(DownloadItem, DownloadItem AdminOptions)
将您的模型设置为具有主模型和具有主模型外键的辅助模型:
class DownloadItem(models.Model):
name = models.CharField( etc etc)
... other attributes here ...
class DownloadItemFile(models.Model):
parent = models.ForeignKey('DownloadItem', related_name="versions")
version = models.CharField( etc etc)
file = models.FileField(upload='path/to/uploaddir/')
然后,当您拥有DownloadItem模型的实例时,您可以使用以下工具获得各种文件版本:
mydownloaditem.versions.all()
为了能够通过管理员添加文件,您需要使用内联。在有关应用程序的admin.py中,您需要添加以下内容:
class DownloadItemFileInline(admin.TabularInline):
model = DownloadItemFile
class DownloadItemAdminOptions(admin.ModelAdmin):
inlines = [ DownloadItemFileInline, ]
...other admin options here...
admin.site.register(DownloadItem, DownloadItem AdminOptions)
你好,史蒂夫贾利姆:谢谢你的回答。它起作用了。但是当我进入管理页面,添加“DownloadItem”时,如何显示其中包含的版本?我如何在DownloadItem页面中直接添加DownloadItemFile?你好stevejalim:谢谢你的回答。它起作用了。但是当我进入管理页面,添加“DownloadItem”时,如何显示其中包含的版本?如何在DownloadItem页面中直接添加DownloadItemFile?