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

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

【问题讨论】:

    标签: python django django-admin


    【解决方案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中所述

    【讨论】:

      猜你喜欢
      • 2018-03-29
      • 2019-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-21
      • 2020-04-20
      相关资源
      最近更新 更多