Home > Mobile >  One to many model POST using API View
One to many model POST using API View

Time:07-29

I have this model

One to many model

I want to POST this to my location endpoint

{
"location": {
    "latitude": "1.23456789",
    "longitude": "1.23456789",
    "resources": [
        {
            "url": "s3/locations/1/es.mp4",
            "name": "lorem_1"
        },
        {
            "url": "s3/locations/1/en.mp4",
            "name": "lorem2"
        }
    ]
}

My goal is to add a location with many resources and to do it through a single locations endpoint using API Views

This is my view:

class LocationView(APIView, api_settings.DEFAULT_PAGINATION_CLASS):
    queryset = Location.objects.all()
    permission_classes = (permissions.AllowAny, )
    serializer_class = LocationSerializer

    def post(self, request):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return response.Response(request.data)

And this is my serializer:

class LocationSerializer(serializers.ModelSerializer):
resources = ResourceSerializer(source='resource_set', many=True, read_only=True)

class Meta:
    model = Location
    fields = ('id', 'latitude', 'longitude', 'resources')

CodePudding user response:

Nested serializers are read-only, you will need to override the create method.

# serializers.py

class LocationSerializer(serializers.ModelSerializer):
    resources = ResourceSerializer(source='resource_set', many=True, read_only=True)

    def create(self, validated_data):
        resources_data = validated_data.pop('resources')
        location = Location.objects.create(**validated_data)
        for resource in resources_data:
            Resource.objects.create(location=location, **resource)
        return location

    class Meta:
        model = Location
        fields = ('id', 'latitude', 'longitude', 'resources')

The same goes for the update method.
More details in the official documentation.

  • Related