1

I am new with Django and Django rest framework, I try to create several routes to get the data from the database.

Right now in my urls.py file I have this

router = routers.DefaultRouter()
router.register(r'cpuProjects', cpuProjectsViewSet, base_name='cpuProjects'),

this return this

"cpuProjects": "http://127.0.0.1:8000/cpuProjects/"

and I have the possibility to do this http://127.0.0.1:8000/cpuProjects/ => return all project http://127.0.0.1:8000/cpuProjects/ad => return a particular project.

In my view.py I have this

class cpuProjectsViewSet(viewsets.ViewSet):
  serializer_class = serializers.cpuProjectsSerializer
  # lookup_field = 'project_name'
  lookup_url_kwarg = 'project_name'

  def list(self, request):
    all_rows = connect_database()
    serializer = serializers.cpuProjectsSerializer(instance=all_rows, many=True)
    return Response(serializer.data)

  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)

Now I want that my Url accepted something like that

http://127.0.0.1:8000/cpuProjects/ad/comments http://127.0.0.1:8000/cpuProjects/ad/ussing http://127.0.0.1:8000/cpuProjects/ad/process

For this I add this new url

router.register(r'cpuProjects/([a-zA-Z0-9]+)$', cpuProjectsViewSet, base_name='cpuProjects'),

but now when I try this

http://127.0.0.1:8000/cpuProjects/ad/ussing

I obtain "page no found"

I understood that this URL have to call to retrieve function to get the parameters, so, why this error?

This URL don't do the same process like

http://127.0.0.1:8000/cpuProjects/ad 

Thanks in advance!

2 Answers 2

1

This is somewhat similar to what we did in our earlier Q&A

from rest_framework.decorators import detail_route, list_route
@detail_route(url_path='(?P<slug>[\w-]+)/(?P<what>[\w-]+)')
def get_by_name(self, request, pk=None,slug=None, what=None):
    print(slug, what)

Similarly you can do the same for a list_route

Sign up to request clarification or add additional context in comments.

Comments

0

The routers framework isn't meant to be used with several parameters .. you can manually do it with primary keys (in the regular expressions).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.