简体   繁体   中英

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

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

Can you try this code

from rest_framework import mixins

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

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM