【问题标题】:How to get results of only the primary key and not all results in django-rest-framework?如何仅在 django-rest-framework 中获取主键而不是所有结果的结果?
【发布时间】:2020-09-03 13:47:21
【问题描述】:

在我的 django 应用程序中,我需要使用电话号码检查用户是否存在。使用电话号码和 OTP 完成登录。 我可以通过获取请求来检查用户是否存在

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

但是如果我要求

"/api/profiles/"

我得到了数据库中所有用户的列表。

如果请求,我需要我的应用不返回任何内容

"/api/profiles/"

如果需要,还有用户详细信息

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

我该怎么做?

序列化器是一个基本模型序列化器


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",
        ]

网址:


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

观看次数:

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

【问题讨论】:

  • 你能贴出你的代码吗
  • 添加了序列化器、视图和urls代码

标签: python django rest django-rest-framework django-rest-knox


【解决方案1】:

你能试试这个代码吗

from rest_framework import mixins

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

【讨论】:

    【解决方案2】:

    我无法使用序列化程序找到任何答案。 因此,我创建了一个基于函数的视图,该视图使用表单数据获取电话号码,并在每次发出请求且用户存在时将密码更新为随机的 6 位 otp。

    检查用户:

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

    【讨论】:

      猜你喜欢
      • 2018-10-19
      • 2022-12-10
      • 1970-01-01
      • 2016-08-03
      • 2018-01-12
      • 1970-01-01
      • 1970-01-01
      • 2017-09-06
      • 1970-01-01
      相关资源
      最近更新 更多