I have created an api where
#urls.py
router = DefaultRouter()
router.register('login', GetUserViewSet, basename='get_user')
urlpatterns = [
path('', include(router.urls)),
]
#views.py
class GetUserViewSet(viewsets.ReadOnlyModelViewSet):
queryset = User.objects.all()
serializer_class = GetProfileSerializer
#serializers.py
class GetProfileSerializer(serializers.ModelSerializer):
class Meta:
model = User
exclude = ('password', 'groups', 'user_permissions')
The above code returns the list of users when I hit 'http://localhost:8000/api/login/' and the specific user when I hit 'http://localhost:8000/api/login/1/'.
Here I want to pass the 'mobile_number' to the api and return the only user with the mobile number.
I have achieved it by adding get_queryset() to the views as follows.
#views.py
class GetUserViewSet(viewsets.ReadOnlyModelViewSet):
queryset = User.objects.all()
serializer_class = GetProfileSerializer
def get_queryset(self):
mobile_number = self.request.query_params.get('mobile_number')
queryset = User.objects.filter(mobile_number=mobile_number)
return queryset
But the above code is returning the object in an array.
I am following a common response format as given below
{
"status": true,
"message": "Successfully registered your account.",
"data": {
"id": 1,
"first_name": "User",
"last_name": "U",
"email": "user@gmail.com",
"dial_code_id": "91",
"mobile_number": "9876543211",
}
}
and I am not able to achieve this with this get_queryset().
Please suggest me the best possible way to achieve this.