'Save multiple objects serializers only if both of them are valid

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).

by default DJANGO save tripserializer. then if error occors in imageserializer,it keep tripserializer in database.

so how can save them only if they are valid both of them?

def post_images(trip_id,data):
      data['trip']=trip_id
      imageserializer = TripImageSerializer(data = data)
      if serializer.is_valid():
           imageserializer.save()
           return Response(status = status.HTTP_201_CREATED)
      return Response({'images':imageserializer.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 tripserializer.is_valid():
                instance = tripserializer.save()
                respo=post_images(instance.pk,dataImg)
                if respo.status_code==400: return respo
         return Response(tripserializer.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",
}


Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Brian Destura