class ImportVS(vs.ViewSet):
def create_and_update(self, request):
"""Creates objects in the database if there is a MODEL and SERIALIZER"""
if not isinstance(request.data, list):
return Response({'error': 'Data must be a list'},
status=status.HTTP_400_BAD_REQUEST)
errors = []
for data in request.data:
for model, values in data.items():
try:
_serializer_class = eval(f'{model}Serializer')
except NameError:
return Response({
'error': f'Serializer {model}Serializer does not exist'},
status=status.HTTP_400_BAD_REQUEST)
_model_class = eval(model)
try:
obj = _model_class.objects.get(pk=int(values['id']))
serializer = _serializer_class(obj, data=values)
except _model_class.DoesNotExist:
serializer = _serializer_class(data=values)
if serializer.is_valid():
serializer.save()
else:
errors.append({'serializer': _serializer_class.__name__,
'errors': serializer.errors})
if errors:
return Response(errors, status=status.HTTP_400_BAD_REQUEST)
return Response(status=status.HTTP_201_CREATED)