How to get results of only the primary key and not all results in django-rest-framework?

468 views Asked by At

In my django app, i need to check if a user exists using a phone number. The login is done using phone number and OTP. I can check if the user exists by a get request to

"/api/profiles/<primary key here>/".

However if I request

"/api/profiles/"

i get a list of all the users in the database.

I need my app to return nothing if requesting

"/api/profiles/"

and user details if requesting

"/api/profiles/<primary key here>/"

How do I do this?

The serializer is a basic model serializer


class UserProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserProfile
        fields = [
            "id",
            "is_superuser",
            "fullname",
            "email",
            "is_staff",
            "is_active",
            # "birthdate",
            "phone_number",
            "created_at",
            "updated_at",
        ]

Urls:


router = routers.DefaultRouter()
router.register(r"profiles", views.UserProfileViewSet)


urlpatterns = [
    path("admin", admin.site.urls),
    path("restauth/", include("rest_framework.urls", namespace="restauth")),
    path("api/", include(router.urls)),

views:

class UserProfileViewSet(viewsets.ModelViewSet):
    queryset = UserProfile.objects.all()
    serializer_class = UserProfileSerializer
2

There are 2 answers

0
Achintya Ranjan Chaudhary On

Can you try this code

from rest_framework import mixins

class UserProfileViewSet(viewsets.ViewSet, mixins.RetrieveModelMixin):
queryset = UserProfile.objects.all()
serializer_class = UserProfileSerializer
0
Tushar Kulkarni On

I was unable to find any answers doing it using serializers. So i made a function based view that took in the phone number using form-data, and updated the password as a random 6 digit otp each time the request was made and the user existed.

Checking the user:

try:
    UserProfiles.objects.get(phone_number=request.POST["phone_number"]
    # generate otp
    return HttpResponse(otp)
except:
    return HttpResponse("user not found")