如何使用Django中的自定义管理命令将数据(从CSV文件)填充到sqlite数据库中?

时间:2019-02-13 10:43:26

标签: django django-models

我正在尝试读取csv文件并将其数据填充到sqlite数据库中。但是,当我检查是否插入了数据时,它返回空的“ QuerySet []”。

这是我的代码:

from django.core.management.base import BaseCommand
import csv
from students.models import Student

class Command(BaseCommand):
    help = 'import data'

    def handle(self, *args, **options):
       file = "../students/data.csv"
       with open(file,newline='', encoding='utf-8') as f:
           reader = csv.reader(f)
           for w in reader:
               created = Student.objects.update_or_create(student_id = int(w[0]), gender = w[1], dob=w[2])
               created.save()

2 个答案:

答案 0 :(得分:0)

  • update_or_create将返回student: Student, created: boolean而不是created: boolean
  • 所有行的缩进量应相同。
  • created.save()是不必要的。 update_or_create()将自动保存您的对象。

如果仍然不起作用。调试w的结果。

亲切的问候。

答案 1 :(得分:0)

from __future__ import print_function

import os
import csv

from django.core.management.base import BaseCommand

from students.models import Student


class Command(BaseCommand):
    help = 'import data'

    def add_arguments(self, parser):
        pass
        # this is optional so that your management command can just accept the
        # path of the csv instead of a hardcoded path
        # parser.add_argument(
        #     'csv_file',
        #     help='path to csv file',
        #     type=str)

    def handle(self, *args, **options):
        # (OPTIONAL) please read the comment above
        # csv_file = options.get('csv_file', '')
        csv_file = '../students/data.csv'

        if not os.path.isfile(csv_file):
            print('file not found!')
            return

        with open(csv_file, newline='', encoding='utf-8') as f:
            reader = csv.DictReader(f)
            for row in reader:
                # update_or_create will return a tuple
                # first item is the student instance
                # the second identifies if the student is newly created or
                # not(updated)
                student, created = Student.objects.update_or_create(
                    student_id=int(row['student_id']), gender=row['gender'],
                    dob=row['dob'])

注意事项:

  • update_or_create返回一个元组(x,y),其中x是模型实例,y是布尔值(如果该事务是否创建了新的Student)。
  • csv的路径相对于您调用manage.py的位置(不确定)

示例目录

└── app
    ├── manage.py
    ├── student.csv

# you can then have
csv_file = 'student.csv'

# and this is what your code above is expecting

└── app
    ├── manage.py
└── student
    ├── student.csv