0

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.

Aryan VR
  • 189
  • 1
  • 12

1 Answers1

0

add .first() to the end of your filter to return the first object in the query set.

Henty
  • 603
  • 2
  • 7
  • Not working. Got the error: TypeError at /api/login/ 'User' object is not subscriptable – Aryan VR Jun 02 '21 at 13:35
  • don't use the get QuerySet method for it, it expects a QuerySet to be returned where an object is an object – Henty Jun 02 '21 at 13:55
  • Can you please share a sample code? I'm getting a little confused with this. – Aryan VR Jun 03 '21 at 05:24
  • sorry i need you to show me more of what you're looking to do. Where do you handle the data from the queryset to send in the dict? or simply where do you call def get_queryset(self): – Henty Jun 03 '21 at 10:41