Based on the given data object i have put below. I wanted to ask how to bulk insert in django or create multiple data. I have provided below including my serializer and python code. I wanted to create/insert every password from the data object which is in below. Dont worry about the other data. Also i want to do it with serializer. I did try to loop through data which is for each_employee_data in data: . Any problem with my code. Thank you.
code
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("each_employee_data", 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=each_employee_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)
Serializer
class UserSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
is_staff = serializers.BooleanField(required=False)
is_confirmed = serializers.BooleanField(required=False)
is_applicant = serializers.BooleanField(required=False)
email = serializers.EmailField(required=True,validators=[UniqueValidator(queryset=User.objects.all(), message="Email already exist.")])
verification_code = serializers.CharField(required=False)
password_reset_code = serializers.CharField(required=False)
def create(self, validated_data):
"""
Create and return a new `Snippet` instance, given the validated data.
"""
password = validated_data.pop("password")
return User.objects.create(password=password,**validated_data)
Data:
[
{
'mname':'Tap',
'email':'[email protected]',
'is_applicant':True,
'lname':'world',
'fname':'hello',
'password':'helloworld12345'
},
{
'mname':'van',
'email':'[email protected]',
'is_applicant':True,
'lname':'asdas',
'fname':'hellworld124344',
'password':'asdasdasdas'
}
]