I'm looking for a way to use the serializer context defined in the ModelViewSet using the get_serializer_context to be used in the queryset declaration of a specific SlugRelatedField:
class ReservationViewSet(ViewPermissionsMixin, viewsets.ModelViewSet):
serializer_class = ReservationSerializer
def get_queryset(self):
code = self.kwargs['project_code']
project= Project.objects.get(code=code)
queryset = Reservation.objects.filter(project=project)
return queryset
def get_serializer_context(self):
return {"project_code": self.kwargs['project_code'], 'request': self.request}
In all serializer methods this is accessible using self.context, but I would like to filter the queryset of this field using this info in the context dictionary:
class ReservationSerializer(serializers.ModelSerializer):
project= serializers.SlugRelatedField(slug_field='code', queryset=Project.objects.all(), required=False)
storage_location = serializers.SlugRelatedField(slug_field='description', queryset=StorageLocation.objects.filter(project__code = context['project_code'])), required=False)
Here the queryset applied to the StorageLocation (project__code = context['project_code']) is where my current issue lies.
Some additional context: this issue is an attempt to resolve the following error from the rest_framework (the StorageLocation queryset was set to .all()):
projects.models.procurement.StorageLocation.MultipleObjectsReturned: get() returned more than one StorageLocation -- it returned 2!