此视图是否正确完成?

时间:2017-07-17 08:05:04

标签: python django python-3.x django-views django-rest-framework

我打算为URL创建视图:url(r'^users/(?P<user_id>[0-9]+)/objects$', views.UserObject)来创建,更新,删除或显示用户的对象。此外,每个用户只能拥有一个对象。我很感激你是否可以看看并告诉我它是否正确完成。

@api_view(['GET', 'POST', 'PUT', 'DELETE'])
def UserObject(request, user_id):

    if request.method == 'POST':

        try:
            Object.objects.get(user=user_id)
            return Response(status=status.HTTP_403_FORBIDDEN)

        except Object.DoesNotExist:
            serializer = ObjectSerializer(data=request.data)
            serializer.fields['user'].required = False
            if serializer.is_valid():
                serializer.save(user_id=user_id)
                return Response(serializer.data, status=status.HTTP_201_CREATED)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    try:
      object = Object.objects.get(user=user_id)
    except Object.DoesNotExist:
      return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
      serializer = ObjectSerializer(object)
      return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = ObjectSerializer(object, 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':
        object.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

更新 views.py:

from rest_framework import viewsets

    class ObjectViewSet(viewsets.ModelViewSet):
        queryset = Object.objects.all()
        serializer_class = ObjectSerializer

urls.py:

url(r'^users/(?P<user_id>[0-9]+)/objects$', views.ObjectViewSet),

1 个答案:

答案 0 :(得分:1)

这正是View sets的目的..

  

ModelViewSet类继承自GenericAPIView,并通过混合各种mixin类的行为来包含各种操作的实现。

这里没有太多特殊逻辑,所以

class ObjectViewSet(viewsets.ModelViewSet):
    queryset = Object.objects.all()
    serializer_class = ObjectSerializer

看起来就像你需要的一切