[Django]-Delete Member of Many To Many Relationship Django Rest Framework

5👍

My favorite approach to this problem would be to create a detail route endpoint on your viewset made for this. Here’s an example of how that might look:

# Views
class TeamViewSet(viewsets.ModelViewSet):
    queryset = Team.objects.all()
    serializer_class = TeamSerializer

    @action(methods=['delete'], detail=True)
    def remove_players_from_team(self, request):
        team = self.get_object()
        players_to_remove = request.data['players']
        # ...

From there, you could add your logic to remove players from the team. The endpoint would be something along the lines of: <base_url>/api/teams/<team_id>/remove_players_from_team and would expect the argument players and a request type of DELETE, which you can expect any number of ways.

This can be applied to also add players, and could be applied on the reverse relation if desired.

As for which method to allow, think about what’s being done. If it’s adding players, prefer a POST request. If it’s removing them, prefer a DELETE. If you want them to be considered as updating, then use PATCH.

If you’re interested in using this, check out the DRF documentation.

Leave a comment