python - 如何在 Django 模型中添加动态字段?

标签 python database django

我正在使用 django 创建一个应用程序下载站点。我尝试编写一个模型,管理员可以在管理页面中动态添加不同的下载内容。例如我有一个名为 foobar 的软件,它有 3 个不同的版本:1.1、1.2、1.3。我希望用户可以通过使用添加按钮添加带有下载版本的下载链接来管理模型。但我不知道如何在 django 中做到这一点。

最佳答案

将模型设置为具有主模型和具有主模型外键的辅助模型:

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) 

关于python - 如何在 Django 模型中添加动态字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2825435/

相关文章:

java - MongoDB 最佳实践——获取集合

sql - Postgres 使用另一行数据更新列

reactjs - webpack-cli不能同时运行多个命令

python - 如何使 Django ManyToMany 'through' 查询更高效?

python - 使用 nosetests 运行 Django 测试

Python - 创建有意义的崩溃日志/崩溃报告

python - 属性错误 : module 'pandas' has no attribute '__version__'

python - 如何使用Python工作池处理并发变量写入

python - 如何处理名称冲突 collections.Counter 和 typing.Counter?

sql - 使用什么作为 ID 和 PK