I'm new to the Django and the Django Rest Framework, and having some issues figuring this one out.
I've got a Model of Workouts
, which contains a title and a many to many relationship field exercises
.
When making the api for the model, I'm inheriting the viewsets.ModelViewSet
class - which from my understanding setups the common uses for a rest api (List, Create, Update etc.).
This is fine however, when accessing /api/workouts/
I get a list of all the workouts including all the exercises assigned to the workout, I feel it's a bit of a waste to pull in all that exercise data and the user might never see it.
I would prefer to have a the /api/workouts/
not return exercises
and it only does so if a user accesses a workout with /api/workouts/1
the exercises will show up.
My serializer class,
class WorkoutSerializer(serializers.ModelSerializer):
exercises = ExerciseSerializer(read_only=True, many=True)
class Meta:
model = Workout
fields = ('id', 'title', 'exercises')
My view,
class WorkoutView(viewsets.ModelViewSet):
queryset = Workout.objects.all()
serializer_class = WorkoutSerializer
def list(self, request):
workouts_list = self.get_queryset().defer('exercises');
serializer = self.get_serializer(workouts_list, many=True)
return response.Response(serializer.data)
My latest attempt is to overwrite the list method and remove the field with the queryset, but it seems anything I do remove the field has no affect.
TL;DR I would like to keep using the ModelViewSet
but remove the field exercises
from the main list view /api/workouts/
and keep it in the detail view /api/workouts/1/
Thanks in advance, for any suggestions.