3

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'
   }
]

1 Answer 1

1

When a serializer is instantiated and many=True is passed, a ListSerializer instance will be created. The serializer class then becomes a child of the parent ListSerializer. The ListSerializer class provides the behavior for serializing and validating multiple objects at once.

There are a few use cases when you might want to customize the ListSerializer behavior. In your case you want the ListSerializer to do a bulk update. You need to define a new custom ListSerializer

class CustomListSerializer(serializers.ListSerializer):
    ...

    def create(self, validated_data):
        ...

class CustomSerializer(serializers.Serializer):
    ...
    class Meta:
        list_serializer_class = CustomListSerializer

In your case it should be

class UserListSerializer(serializers.ListSerializer):
        ...

        def create(self, validated_data):
            user = [User(**item) for item in validated_data]
            return User.objects.bulk_create(User)



class UserSerializer(serializers.Serializer):
            ...
            class Meta:
                list_serializer_class = UserListSerializer

https://www.django-rest-framework.org/api-guide/serializers/#customizing-listserializer-behavior

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.