Created
October 24, 2019 17:00
-
-
Save alisonamerico/5b162ddccc70bd3bc4c53be3fe36da2b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
``` | |
views.py | |
from django.db.models import F | |
from rest_framework.exceptions import ValidationError | |
from rest_framework import viewsets | |
from rest_framework.response import Response | |
from rest_framework.status import HTTP_201_CREATED, HTTP_409_CONFLICT, HTTP_400_BAD_REQUEST | |
from .models import GlobalVariable, Variable, Unity, State | |
from .serializers import GlobalVariablesSerializer, StateSerializer, ConflictError | |
class IcmsAliquotViewSet(viewsets.ModelViewSet): | |
queryset = GlobalVariable.objects.filter(variable_id__name__exact='ICMS').annotate(variable_name=F('variable_id__name'), state_name=F('state_id__name'), unity_type=F('unity_id__name')) | |
serializer_class = GlobalVariablesSerializer | |
def create(self, request, *args, **kwargs): | |
try: | |
GlobalVariablesSerializer(data=[data for data in request.data if data.get('id') is not None], many=True).update(instance=GlobalVariable.objects.select_for_update().all(), validated_data=list(filter(lambda data: data.get('id') is not None, request.data))) | |
new_variables = GlobalVariablesSerializer(data=[data for data in request.data if data.get('id') is None], many=True) | |
new_variables.is_valid(True) | |
new_variables.save() | |
except ValidationError: | |
return Response ('qualquer coisa', HTTP_400_BAD_REQUEST) | |
except ConflictError as conflict_error: | |
return Response(conflict_error.detail, HTTP_409_CONFLICT) | |
return Response({'message': 'Success!'}, HTTP_201_CREATED) | |
``` | |
Cenário: | |
Tenho uma lista de ESTADO | VALOR DE ICMS(%) | |
Estou querendo fazer a seguinte validação: | |
1 - Não permitir inserir um mesmo estado(por exemplo "PERNAMBUCO"), se já existir esse valor na lista, nesse caso deve retornar uma crítica, informando que já exite o estado. | |
2 - Se o estado não existir na lista, inserir o mesmo. retornar sucesso. | |
3 - Se já existir e quiser apenas atualizar. retornar sucesso. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment