我正在尝试读取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()
答案 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)。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