Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I PATCH Django REST Framework PrimaryKeyRelatedField to empty list?

I'm running into a weird issue in Django REST Framework. I'm attempting to add & remove groups to/from users using PATCH requests.

I am able to PATCH to /api/users/:id/ to update the groups list, which is initially empty. For example, the following actions yield these results:

  1. PATCH /api/users/:id/ {"groups": [1]} -> Results in user with groups: [1]
  2. PATCH /api/users/:id/ {"groups": [1, 2]} -> Results in user with groups: [1,2]
  3. PATCH /api/users/:id/ {"groups": [1]} -> Results in user back to groups: [1]

So I am successfully updating the state with PATCH requests. However the following fails to update accordingly:

PATCH /api/users/:id/ {"groups": []} -> Results in user still at groups: [1]

Here is my UserSerializer class:

class UserSerializer(serializers.ModelSerializer):
    groups = serializers.PrimaryKeyRelatedField(many=True,
                                                queryset=Group.objects.all(),
                                                allow_empty=True, required=False)

    class Meta:
        model = User
        fields = (
            'id',
            'username', 'first_name', 'last_name', 'is_staff', 'is_authenticated', 'is_superuser', 'email',
            'groups'
        )

My suspicion is that it has something to do with PrimaryKeyRelatedField - I have tried many combinations of arguments to the constructor to no avail.

like image 409
c_sagan Avatar asked Sep 14 '25 00:09

c_sagan


1 Answers

This was actually due to a bug in the partial_update override in the UserViewSet

PATCH works as expected after fixing this issue, and users using the default partial_update Django REST Framework provides shouldn't experience this issue.

like image 161
c_sagan Avatar answered Sep 15 '25 12:09

c_sagan