Как использовать bulk_create в django

Я только что узнал, что могу использовать bulk_create в django, чтобы запрос не был слишком длинным и выполнялся быстро, а не использовать for loop для добавления данных в базу данных по одному.

Проблема в том, что я не знаю, как это сделать, пожалуйста, помогите мне.

views.py:

    if request.method == "POST":
        csv_form = UploadCSVFileForm(request.POST or None, request.FILES or None)
        if csv_form.is_valid():
            period = csv_form.cleaned_data.get('period')
            print(period)
            period = SchoolPeriod.objects.get(period = period)
            # save csv file
            uploaded_file = csv_form.cleaned_data.get('file_name')
            save_csv = GradeCSVFile.objects.create(file_name= uploaded_file)

            csv_file = GradeCSVFile.objects.get(grades_uploaded= False)

            #read csv file
            with open(csv_file.file_name.path, 'r') as file:
                reader = csv.reader(file)

                for i, row in enumerate(reader):
                    if i == 0:
                        pass
                    else:
                        subject = Subject.objects.get(subject_name = row[3])
                        profile = get_object_or_404(StudentProfile, LRN_or_student_number = row[0])


         ######### **THIS IS THE PART WHERE I NEED THE `BULK_CREATE` ** ############
                        new_grade = StudentGrade.objects.create(
                            student=profile.student.student,
                            period = period,
                            subject = subject,
                            grade = row[4],
                            )

            csv_file.grades_uploaded = True
            csv_file.save()

Я понял, что нужно делать здесь:

  1. instantiate an empty list
  2. loop over the rows in csv file
  3. while looping through the rows, instantiate the object and assign it to a variable.
  4. while looping through the rows append the variable to the list
  5. after the loop: obj = mymodel.objects.bulk_create(list)

код:

            grade_list = []
            #read csv file
            with open(csv_file.file_name.path, 'r') as file:
                reader = csv.reader(file)

                for i, row in enumerate(reader):
                    if i == 0:
                        pass
                    else:
                        subject = Subject.objects.get(subject_name = row[3])
                        profile = get_object_or_404(StudentProfile, LRN_or_student_number = row[0])

                        new_grade = StudentGrade(
                            student=profile.student.student,
                            period = period,
                            subject = subject,
                            grade = row[4],
                            )

                        grade_list.append(new_grade)

                        # this is slow
                        # new_grade = StudentGrade.objects.create(
                        #     student=profile.student.student,
                        #     period = period,
                        #     subject = subject,
                        #     grade = row[4],
                        #     )
                new_grades = StudentGrade.objects.bulk_create(grade_list)

Если вы не хотите использовать bulk_create, вы можете использовать transaction.atomic:

from django.db import transaction
                   with transaction.atomic():
                        new_grade = StudentGrade(
                            student=profile.student.student,
                            period = period,
                            subject = subject,
                            grade = row[4],
                            )
                        new_grade.save()

Вернуться на верх