
from rest_framework import viewsets
from .. import models, serializers
from django.db.models import Max

class ComunaViewSet(viewsets.ModelViewSet):
    queryset = models.Comuna.objects.all()
    serializer_class = serializers.ComunaSerializer

    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_comuna', None):
            max_id = models.Comuna.objects.aggregate(Max('id_comuna'))['id_comuna__max']
            new_id = max_id + 1 if max_id is not None else 1
            request.data['id_comuna'] = new_id
        
        return super().create(request, *args, **kwargs)