Django REST - separating valid data from non-valid and serializing the former with many=True

149 Views Asked by At

I am using Django REST framework to come up with a REST api for my app. In one of my views, I am trying to use many=True when initializing my serializer object in order to bulk_insert multiple rows at once. The problem is that if one of the records in the dataset is invalid, serializer's is_valid() method return False, thus rejecting the entire dataset. Whereas the desired behavior would be inserting valid records and ignoring invalid ones. I have succeed in achieving this using the following code, but I have a terrible feeling that this is junk code and the REST framework has a native way to do this.

My code below (that I consider junk code :)):

serializers.py

class MySerializer(serializers.ModelSerializer):
    class Meta:
        model = CalendarEventAttendee
        fields = '__all__'

view.py

def my_view(request):
    validated_data = []
    # Separate valid data from invalid
    for record in request.data:
        if MySerializer(data = record).is_valid():
            validated_data.append(record)

    # bulk_insert valid data    
    serializer = MySerializer(data=validated_data, many=True)
    if serializer.is_valid():
        serializer.save()

Can anyone suggest a better approach ?

0

There are 0 best solutions below