using django rest framework to return info by name
<p>I am using Django rest framework  and I create this class to return all the name of project</p>

<pre><code>class cpuProjectsViewSet(viewsets.ViewSet):
  serializer_class = serializers.cpuProjectsSerializer

  def list(self, request):
    all_rows = connect_database()
    name_project = [] 
    all_projects = []
    for item_row in all_rows:
      name_project.append(item_row['project'])
      name_project = list(sorted(set(name_project)))
    for i in range(0, len(name_project)):
      all_projects.append({'project' : str(name_project[i])})

    serializer = serializers.cpuProjectsSerializer(instance=all_projects, many=True)
    return Response(serializer.data)
</code></pre>

<p>my URL is like that  <code>http://127.0.0.1:8000/cpuProjects/</code>  this return all the projects, buy If now I want a particular project, Have I to create a new class?? if I  want to use the same URL ... for example
<code>http://127.0.0.1:8000/cpuProjects/</code> => return all project
<code>http://127.0.0.1:8000/cpuProjects/nameProject</code> => return a particular project.</p>

<pre><code>class cpuProjectsViewSet(viewsets.ViewSet):
  serializer_class = serializers.cpuProjectsSerializer
  lookup_field = 'project_name'

  def retrieve(self, request, project_name=None):
    try:
      opc = {'name_proj' : project_name }
      all_rows = connect_database(opc)
    except KeyError:
        return Response(status=status.HTTP_404_NOT_FOUND)
    except ValueError:
        return Response(status=status.HTTP_400_BAD_REQUEST)
    serializer = serializers.cpuProjectsSerializer(instance=all_rows, many=True)
    return Response(serializer.data)
</code></pre>

<p>Is it possible to do in the same class? I try to use retrieve method but the need an ID of the project, no the name right?   </p>

<p>thanks in advance!</p>

<p>If you want to use the same class you can use a viewset and define a list() and retrieve() methods</p>

<p>check <a href="http://www.django-rest-framework.org/api-guide/viewsets/" rel="nofollow">http://www.django-rest-framework.org/api-guide/viewsets/</a> the first example is doing that</p>

<pre><code>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):
    """
    A simple ViewSet for listing or retrieving users.
    """
    def list(self, request):
        queryset = User.objects.all()
        serializer = UserSerializer(queryset, many=True)
        return Response(serializer.data)

    def retrieve(self, request, pk=None):
        queryset = User.objects.all()
        user = get_object_or_404(queryset, pk=pk)
        serializer = UserSerializer(user)
        return Response(serializer.data)
</code></pre>

python django django-rest-framework