from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from django.shortcuts import get_object_or_404 from .models import Metric from .serializers import MetricSerializer, MetricListSerializer @api_view(['GET', 'POST']) def metric_list(request): user = request.user if request.method == 'GET': metrics = Metric.objects.all() serializer = MetricListSerializer(metrics, many=True) return Response(serializer.data) elif request.method == 'POST': if Metric.objects.filter(user=user).exists(): return Response({'detail': 'Metric already exists for this user.'}, status=status.HTTP_400_BAD_REQUEST) serializer = MetricSerializer(data=request.data) if serializer.is_valid(): serializer.save(user=user) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['GET', 'PUT', 'DELETE']) def metric_detail(request): user = request.user if request.method == 'GET': metric = get_object_or_404(Metric, user=user) serializer = MetricSerializer(metric) return Response(serializer.data) elif request.method == 'PUT': metric = get_object_or_404(Metric, user=user) serializer = MetricSerializer(metric, 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': metric = get_object_or_404(Metric, user=user) metric.delete() return Response({'detail': 'Metric deleted successfully.'}, status=status.HTTP_204_NO_CONTENT)