using django rest framework to return info by name

前端 未结 3 627
栀梦
栀梦 2021-01-22 19:24

I am using Django rest framework and I create this class to return all the name of project

class cpuProjectsViewSet(viewsets.ViewSet):
  serializer_class = seri         


        
3条回答
  •  时光说笑
    2021-01-22 19:57

    You need to add lookup_field in view class. Suppose, you want to get user by username you need to add lookup_field = 'username'.

    Example:

    from django.contrib.auth.models import User
    from django.shortcuts import get_object_or_404
    from myapps.serializers import UserSerializer
    from rest_framework import viewsets
    from rest_framework.response import Response
    
    class UserViewSet(viewsets.ViewSet):
    
        lookup_field = 'username'
    
        def list(self, request):
            queryset = User.objects.all()
            serializer = UserSerializer(queryset, many=True)
            return Response(serializer.data)
    
        def retrieve(self, request, username=None):
            queryset = User.objects.all()
            user = get_object_or_404(queryset, username=username)
            serializer = UserSerializer(user)
            return Response(serializer.data)
    

    Now your url will be

    url(r'^users/$', UserViewSet.as_view({'get': 'list'})),
    url(r'^users/(?P[a-zA-Z0-9]+)$', UserViewSet.as_view({'get': 'retrieve'})),
    

    Now http://127.0.0.1:8000/users/ will return all users and http://127.0.0.1:8000/users/username will return particular user details.

    You can learn more about lookup_field from Django REST framework.

提交回复
热议问题