DRF 子视图快速实现功能的使用方法!

1,ListAPIView继承与GenericAPIView、ListModelMixin
# 对list重写,因为默认只会返回 serializer.data
    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user

        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': 10,
            'addresses': serializer.data,
        })

2,DestroyAPIView继承了GenericAPIView、DestoryModelMixin

#对自带的进行重写,默认会直接删除掉
def delete(self, request, *args, **kwargs):
        # 如果有 pk 值那么就会按照pk值进行查找!
        address = self.get_object()
        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

 

posted @ 2018-06-24 17:23  十七楼的羊  阅读(134)  评论(0编辑  收藏  举报