
from rest_framework import viewsets
from django_filters.rest_framework import DjangoFilterBackend
from django.db.models import Max
from api import models , serializers

class RedTransporteViewSet(viewsets.ModelViewSet):
    queryset = models.RedTransporte.objects.all()
    serializer_class = serializers.RedTransporteSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['id_red', 'nombre_red', 'descripcion','vigente']
    

    def create(self, request, *args, **kwargs):
        # se indica que si no se indico el id, entonces sea el maximo + 1
        if not request.data.get('id_red', None):
            max_id = models.RedTransporte.objects.aggregate(Max('id_red'))['id_red__max']
            new_id = max_id + 1 if max_id is not None else 1
            request.data['id_red'] = new_id
        
        return super().create(request, *args, **kwargs)