django 如何在带有OneToOne字段的URL中添加用户名

hyrbngr7  于 2023-05-01  发布在  Go
关注(0)|答案(1)|浏览(152)

我有模型和序列化程序,我希望API使用用户名而不是pk
我该怎么做?我实际上试图使用查找字段,但这不是真正的工作
models.py

class IndividualUser(models.Model):
    individual_user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    first_name = models.CharField(_("first name"), max_length=150)
    last_name = models.CharField(_("last name"), max_length=150)

urls.py

path('api/profile/<str:individual_user>/', IndividualClientDetailApiView.as_view()),

views.py

class IndividualClientDetailApiView(generics.RetrieveAPIView):
    queryset = IndividualUser.objects.all()
    serializer_class = IndividualClientSerializer
    permission_classes = (IsAuthenticated, IsOwnerOrAdminOrReadOnly)

    lookup_field = 'individual_user'
7ajki6be

7ajki6be1#

你可以这样尝试:

class IndividualClientDetailApiView(generics.RetrieveAPIView):
    queryset = IndividualUser.objects.all()
    serializer_class = IndividualClientSerializer
    permission_classes = (IsAuthenticated, IsOwnerOrAdminOrReadOnly)

    lookup_field = 'individual_user__username'
    lookup_url_kwarg = "individual_user"

这里,通过将lookup_field指向User模型的username,当发出请求时,查询集将在该字段中查找,同时从url(通过lookup_url_kwarg)传递indivisual_user的username值。因此,URL看起来像这样:
localhost:8000/API/profile/myusername/
更多信息可在文档中找到。

相关问题