[Fixed]-Writing a script to enter multiple items into model fields in django shell

1๐Ÿ‘

A custom management command is indeed what you need to perform tasks like this. I would put your data into a CSV file and them import it with something like this:

# myapp/management/commands/import_questions.py
import csv

from django.core.management.base import BaseCommand
from myapp.models import Question

class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument('csvfile', nargs='+', type=str)

    def handle(self, *args, **options):
        for f in options['csvfile']:
            with open(f) as csvfile:
                reader = csv.reader(csvfile)
                for row in reader:
                    # Say the CSV rows are as follows: 
                    # <Question title>, <Answer1Text>, <Answer1Correct> ... etc 
                    q = Question(question_text=row[0])
                    q.save()
                    q.choice_set.create(choice_text=row[1], rorwrong=bool(row[2]))
                    q.choice_set.create(choice_text=row[3], rorwrong=bool(row[4])) 
                    # Etc for the rest of them

You would then execute this command with:

./manage.py import_questions --csvfile data.csv
๐Ÿ‘คsolarissmoke

Leave a comment