Django python使用序列化器is_valid(raise_exception = True)插入多行,插入每个对象

时间:2019-04-17 08:29:17

标签: python django object insert

想在数据库中插入多行,但是我在if user_serializer.is_valid(raise_exception=True):中有错误

我不知道在此行user_serializer = UserSerializer(data=each_employee_data).上是否做错了

目标是将each_employee_data对象插入数据库,这是我在下面的代码中做错的吗?。

要插入的对象(每个员工数据数据)

[  
   {  
      'mname':'Tap',
      'password':'helloworld12345',
      'fname':'asd asd',
      'is_applicant':True,
      'email':'asdsa@gmail.com',
      'lname':'asd'
   },
   {  
      'mname':'van',
      'password':'asdasdasdas',
      'fname':'anthonasdasdasd',
      'is_applicant':True,
      'email':'asdsa@gmail.com',
      'lname':'asdas'
   }
]

代码

def post(self, request, format=None):
        data = request.data

        print("Data::" , data)

        for each_employee_data in data:
            each_employee_data["verification_code"] = verification_code(self)
            password = hashers.make_password(each_employee_data["password"])
            each_employee_data["password"] = password
            print("hahahahaha", each_employee_data)
            user_serializer = UserSerializer(data=each_employee_data)

            if user_serializer.is_valid(raise_exception=True):

                if not each_employee_data["is_applicant"]:#company
                    company_serializer = CompanySerializer(data=data)
                    if company_serializer.is_valid(raise_exception=True):
                        user_ins = user_serializer.save(password=password)
                        company_serializer.save(user=user_ins)
                else:
                    applicant_serializer = ApplicantSerializer(data=data)
                    if applicant_serializer.is_valid(raise_exception=True):
                        user_ins = user_serializer.save(password=password)
                        applicant_serializer.save(user=user_ins)


                send_confirmation.delay(data)
                if not user_ins.is_applicant:
                    send_business_confirmation.delay(data)

0 个答案:

没有答案