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:
PATCH /api/users/:id/ {"groups": [1]} -> Results in user with groups: [1]PATCH /api/users/:id/ {"groups": [1, 2]} -> Results in user with groups: [1,2]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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With