如何在多个字段中使用[PUT,UPDATE,DELETE]?

时间:2018-04-09 06:24:15

标签: django django-rest-framework

在这里,他们使用pk获取代码段,但我必须通过名称,ID和作者获取。那么如何编写功能视图

@api_view(['GET', 'PUT', 'DELETE'])
def snippet_detail(request, pk):
    try:
        snippet = Snippet.objects.get(pk=pk)
    except Snippet.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)
    if request.method == 'GET':
        serializer = SnippetSerializer(snippet)
        return Response(serializer.data)
    elif request.method == 'PUT':
        serializer = SnippetSerializer(snippet, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    elif request.method == 'DELETE':
        snippet.delete()
    return Response(status=status.HTTP_204_NO_CONTENT)

2 个答案:

答案 0 :(得分:0)

def snippet_detail(request, key, val):
    try:
        kw = {key:val}
        snippet = Snippet.objects.get(**kw)
    except:
       //same logic

您还需要更新您的网址。

答案 1 :(得分:0)

你可以用两种(或更多种方式)来做到这一点 方法 - 1

@api_view(['GET', 'PUT', 'DELETE'])
def snippet_detail(request):
    url_params = request.GET  # <<<<<<<<< Change <<<<<<<<<
    try:
        snippet = Snippet.objects.get(**url_params)  # <<<<<<<<< Change <<<<<<<<<
    except Snippet.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    # same code

在这种方法中,您的urls.py必须是这样的,

url(r'some_endpoint/',snippet_detail)

和api将是host/end/point/some_endpoint/?id=123&name=testname&author=test_author


方法 - 2

@api_view(['GET', 'PUT', 'DELETE'])
def snippet_detail(request, *args, **kwargs):
    try:
        snippet = Snippet.objects.get(id=kwargs['id'], name=kwargs['name'], author=kwargs['author'])  # <<<<<<<<< Change <<<<<<<<<
    except Snippet.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    # same code


并且您的urls.py将如下所示,

url(r'some_endpoint/(?P<id>\d+)/(?P<name>\w+)/(?P<author>\w+)/', snippet_detail)

,终点就像,host/end/point/some_endpoint/123/testname/test_author/

注意
问题method-2是,您必须为所有http方法使用相同的网址格式(在您的情况下,GETPUTDELETE