简体   繁体   English

如何在 django-rest-framework 中仅获取主键的结果而不是所有结果?

[英]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.在我的 django 应用程序中,我需要使用电话号码检查用户是否存在。 The login is done using phone number and OTP.登录是使用电话号码和 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.因此,我创建了一个基于函数的视图,该视图使用表单数据接收电话号码,并在每次发出请求且用户存在时将密码更新为随机的 6 位 otp。

Checking the user:检查用户:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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