[Fixed]-Use multiple ModelViewSet for a REST call

1👍

Calling other ModelViewSets is possible, but not recommended (by me). But here’s how you could do it if that’s what you really want to do:

class ViewSet3(ModelViewSet):
    def create(self, request):
        # Preproccess 
          ....

        # Call view 1 & 2
        response1 = ViewSet1.as_view({'post': 'create'})(request)
        response2 = ViewSet2.as_view({'post': 'create'})(request)

However, it’s more likely that you just need a custom create method on your serializer to handle creating all of the other objects, not multiple views (I assume you’re using JSON).

class View3Serializer(serializers.Serializer):
    # my nested fields
    view_1_data = View2Serializer(required=False)
    view_2_data = View3Serializer(required=False)

    def create(self, validated_data):
        view_1_data = validated_data.pop('view_1_data', None)
        view_2_data = validated_data.pop('view_2_data', None)

        # Create my View3 object normally
        instance = View3Model.objects.create(**validated_data)

        # Create other objects with other data here
          ....

        return instance

Leave a comment