altu_faltu
altu_faltu

Reputation: 91

Bulk insertion in django rest framework

When I am trying to create multiple instances in a single request it shows error if one instance is not correct in the batch. But how can I write my create method to insert correct instances in the batch. That means only correct instances will insert in the db and also show the errors message for the wrong instances.

[
    {
        "name": "oil",
        "unit_price": 200
    },
    {
        "name": "meat",
        "unit_type": "raw",
        "unit_price": 1000
    }
        "name": "salt",
        "unit_type": "raw",
        "unit_price": -100
    }

]

I want to insert first two instances will be insert in the db and for last one it will throws an error like this.

    "errors":
 [

        {
            "unit_price": [
                "Enter positive number."
            ]
        }
 ]

Here is my serializer

class ProductSerializer(serializers.ModelSerializer):

    def validate_unit_price(self, value):
         if (value) > 0:
             return value
         raise serializers.ValidationError("Enter positive number.")

    class Meta:
        model  = Product
        fields = [ 'name', 'unit_type', 'unit_price']

Also my views function is

@api_view(['POST'])
def store(request):

    serializer          =   ProductSerializer(data = request.data,many=True)

    if serializer.is_valid():
        serializer.save()
    return Response({'response_code': '500', 'response': status.HTTP_500_INTERNAL_SERVER_ERROR, 'message': 'Something went wrong', 'data': request.data, 'errors': serializer.errors})

Upvotes: 0

Views: 851

Answers (1)

aredzko
aredzko

Reputation: 1730

Since you're using one ProductSerializer instance, you won't be able to save if is_valid returns False. If you want to create all valid datasets and return the ones that errored, you might want to consider creating a serializer instance per entry, and keeping track of the data returned. You can build out a list of response values for the user that way, so partial failure is allowed.

My suggestion will not make this a "bulk" operation, but it technically isn't with many=True. many=True just wraps your serializer with a ListSerializer, which just calls create using the wrapped serializer per attribute. So you're performing a save() per instance of data as is.

Upvotes: 1

Related Questions