我是Django
和Django rest framework
的新手,我尝试创建多条路径来从数据库中获取数据。
现在我的urls.py
文件中有这个
router = routers.DefaultRouter()
router.register(r'cpuProjects', cpuProjectsViewSet, base_name='cpuProjects'),
这返回
"cpuProjects": "http://127.0.0.1:8000/cpuProjects/"
我有可能这样做
http://127.0.0.1:8000/cpuProjects/
=>返回所有项目
http://127.0.0.1:8000/cpuProjects/ad
=>返回一个特定的项目。
在我的view.py中我有这个
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)
现在我希望我的Url接受类似的内容
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
为此我添加了这个新网址
router.register(r'cpuProjects/([a-zA-Z0-9]+)$', cpuProjectsViewSet, base_name='cpuProjects'),
但现在我试试这个
http://127.0.0.1:8000/cpuProjects/ad/ussing
我获得“找不到页面”
我明白这个URL必须调用检索函数来获取参数,那么,为什么会出现这个错误?
此网址不会执行与
相同的过程http://127.0.0.1:8000/cpuProjects/ad
提前致谢!
答案 0 :(得分:1)
这与我们之前的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)
同样,您可以对list_route
答案 1 :(得分:0)
路由器框架并不适用于多个参数。您可以使用主键(在正则表达式中)手动执行此操作。