在 django 中填充字段(添加新的)

Posted

技术标签:

【中文标题】在 django 中填充字段(添加新的)【英文标题】:Populate fields (add new) in django 【发布时间】:2018-12-16 01:26:57 【问题描述】:

如何通过在 django(管理员)中添加新字段来添加相同的内容?: https://gyazo.com/e31dc35495f61032c9605acc3723946b

【问题讨论】:

【参考方案1】:

尝试从python manage.py shell创建对象

1) 从列表、数据框或其他任何内容创建模型的每个实例 - 在您的情况下为足球俱乐部,并将它们存储在列表中:

from django_app.models import ClubToChoose
# read the data from .csv or .txt file, etc. instead of this list
clubs = ['Flamengo', 'foo', 'bar']
# this list will contain your data in django format - as a model instance
clubs_model_instances = []

for club in clubs:
    model_instance = ClubToChoose(choice_text=club,
                                  votes=0)
    clubs_model_instances.append(model_instance)

2) 使用bulk_create() 方法将您的选择添加到数据库:

ClubToChoose.objects.bulk_create(clubs_model_instances)

文档:https://docs.djangoproject.com/en/2.0/ref/models/querysets/#bulk-create

这种方法比逐个创建实例要快得多,如https://docs.djangoproject.com/en/2.0/ref/models/querysets/#create中所述

【讨论】:

以上是关于在 django 中填充字段(添加新的)的主要内容,如果未能解决你的问题,请参考以下文章