Save multiple objects serializers

I have multiple serializers objects that comes from the request as json file. I want to store them inside databases only if they are Valid (all of them must be VALID)

def post_images(trip_id,data):
      data['trip']=trip_id
      serializer = TripImageSerializer(data = data)
      if serializer.is_valid():
           serializer.save()
           return Response(status = status.HTTP_201_CREATED)
      return Response({'images':serializer.errors},status= status.HTTP_400_BAD_REQUEST)
        

class Trip_apiView(generics.ListCreateAPIView):
    queryset= Trip.objects.all()
    serializer_class=TripSerializer
    def post(self, request):
         data = request.data
         dataImg=data.pop('trip_images')
         if serializer.is_valid():
                instance = serializer.save()
                respo=post_images(instance.pk,dataImg)
                if respo.status_code==400: return respo
         return Response({'trip_images' :serializer.errors}, status= status.HTTP_400_BAD_REQUEST)

this is JSON :

{
     "id": 137,
     "trip_images": [
        {"image_title":"image1","image_order":1},
        {"image_title":"image2","image_order":2}
       ],
     "title": "dqw",
     "description": "nice",
     "start_date": "2022-02-08T12:00:00Z",
     "end_date": "2022-02-14T12:00:00Z",
}

If you want the validation to run for the whole json data, you can use TripImageSerializer as the serializer for the trip_images field of TripSerializer:

class TripSerializer(serializers.ModelSerializer):
    trip_images = TripImageSerializer()
    # ...

so if you do:

serializer = TripSerializer(data=request.data)
serializer.is_valid()

is_valid() wil then run the validations for trip_images as well.

Back to Top