[Answered ]-DRF – Filters in ModelSerializer

2👍

Serializer has request object in his context dict. So you can get the current user from there.

 def get_companies(self, obj):
     user = self.context['request'].user
     if user.is_staff:
         serializer = CompanySerializer(Company.objects.all(), many=True)
     else:
         serializer = CompanySerializer(instance=companies, many=True)
     return serializer.data

0👍

To access request object in serializer you need to pass it context dict while initializing serializer i.e in your views.py

serializer = BUserSerializerRelated(request.user, context={'request': self.request})

then in your serializers.py, you can access request user object like

user = self.context['request'].user

Leave a comment