Using PATCH to add a new instance of a nested field when using a RetrieveAPIView in Django Rest Framework

Hello,

I have a set up a route for a RetrieveUpdateAPIView and am testing it in Postman using PATCH.

I am writing a value into a nested field, which is working but deletes all other instances of that nested model.

Here is what I enter in ‘JSON body’ in Postman

{
    "cards": [
        9
    ]
}

When I PATCH the value ‘9’, it deletes all other ‘card’ instances. I was expecting it to simply add that ‘card’ instance without taking the others away.

This is an example of the response:

{
    "id": 19,
    "name": "collector two",
    "email": "two@example.com",
    "cards": [
        9
    ]
}

Here is my view code

class CollectorRetrieveView(generics.RetrieveUpdateAPIView):
    queryset = Collector.objects.all()
    serializer_class = SmallCollectorSerializer
    permission_classes = [HasAPIKey | IsAuthenticated]
    lookup_field = 'email'

Serializer


    class Meta:
        model = Collector
        fields = ["id", "name", "email", "cards"]

Route

path("collector_retrieve/<email>", CollectorRetrieveView.as_view(), name="collector_retrieve"),

I tried to PATCH ‘card’ 9 without deleting the other card instances

The behaviour of ModelSerializer is to replace attributes on update (see https://github.com/encode/django-rest-framework/blob/master/rest_framework/serializers.py#L1047).

If the behaviour was to add new cards on collector updates, how would you specify removal of some cards ?

If you want to achieve your specific behaviour you have to override the update implementation on your serializer. But, for better semantic, maybe you should opt for a ModelViewset with a specific (e.g. add_card) action (see Viewsets - Django REST framework).