5

Here is the way to create and update multiple records at once in django rest framework using ListSerializer. This way is very sort and and give fast response.

When you want to create a objects then pass id: null because id is required field and when you want to update the records then pass specific id.

Here is the answer:

models.py

class BookDetail(models.Model):
    author = models.ForeignKey('bookapp.Author', null=True, on_delete=models.CASCADE)
    title = models.CharField(max_length=255, null=True, blank=True)
    price = models.CharField(max_length=100, null=True, blank=True)
    discount = models.FloatField(default=0)
    tax_percentage = models.IntegerField(default=0)
    total_price = models.FloatField(default=0)

    created_at = models.DateTimeField(auto_now_add=True, editable=False)
    modified_at = models.DateTimeField(auto_now=True)

serializer.py

class BookDetailsListSerializer(serializers.ListSerializer):
    def update(self, instance, validated_data):
        # Perform creations and updates.
        ret = []

        for data in validated_data:
            if "id" in data and data['id'] not in ['', None]:
                BookDetail.objects.filter(id=data['id']).update(**data)
                ret.append(data)
            else:
                ret.append(BookDetail.objects.create(**data))
        return ret

    
class BookDetailsSerializer(serializers.ModelSerializer):
    class Meta:
        model = BookDetail
        fields = ['id', 'author', 'title', 'price', 'discount', 'tax_percentage', 'total_price']
        list_serializer_class = BookDetailsListSerializer
        extra_kwargs = {
            # We need to identify elements in the list using their primary key,
            # so use a writable field here, rather than the default which would be read-only.
            'id':{
                'read_only': False,
                'allow_null': True,
            },
            'author':{
                'required': True,
            },
            'title':{
                'required': True,
            },
            'price':{
                'required': True,
            },
            'discount':{
                'required': True,
            },
            'tax_percentage':{
                'required': True,
            },
            'total_price':{
                'required': True,
            }
        }

urls.py

path('book-details', views.BookDetailsView.as_view()),

views.py

class BookDetailsView(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = (IsAuthenticated,)
    serializer_class = BookDetailsSerializer

    def get(self, request, *args, **kwargs):
        author_id = request.GET.get('author_id', None)
        bookdtl_obj = BookDetail.objects.filter(author__id=a)
        serializer = self.serializer_class(bookdtl_obj, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)
    
    def post(self, request, *args, **kwargs):
        data = request.data
        serializer = self.serializer_class(instance='',data=data, many=True)
        if serializer.is_valid(raise_exception=True):
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Here, I attached screenshot of create multiple book objects using postman:

enter image description here

Here, I attached screenshot of update multiple book objects using postman:

enter image description here

0 Answers0