django rest在不同的url中返回相同的内容

时间:2016-07-09 16:47:47

标签: django django-rest-framework

当我发短信时,我使用httpie测试我的api

localhost:8000/users/

显示用户列表,然后是文本

localhost:8000/users/jack/

它仍显示用户列表,而不是用户详细信息,我的代码有问题吗?

url.py

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('rest_framework.urls',namespace='rest_framework')),
url(r'regist/', Regist.as_view()),
url(r'users/', UserList.as_view()),
url(r'users/(?P<username>[a-zA-Z0-9]+)/$', UserDetail.as_view()),
]

views.py

class UserDetail(generics.ListAPIView):
    serializer_class= UserSeriallizer

    def get_queryset(self):
        username = self.kwargs['username']
        user=User.objects.filter(username=username)
        return user

class UserList(APIView):
    def get(self, request):
        users = User.objects.all()
        serializer = UserSeriallizer(users, many=True)
        return Response(serializer.data)

1 个答案:

答案 0 :(得分:1)

在您的网址中出现问题,您需要关闭r'users/$,因为Django无法users/进一步$ 为什么使用ListAPIView来检索单个对象?
如果要更改数据,则需要RetrieveAPIViewRetrieveUpdateAPIView。并改变你的观点:

class UserDetail(RetrieveAPIView):
    lookup_field = 'username'
    queryset = User.objects.all()

您根本不需要get_queryset

About mixins