[
{
"AttributeName": {
"id": 1,
"title": "color"
}
},
{
"AttributeValue": {
"id": 1,
"value": "red"
}
},
{
"ProductImage": {
"id": 5,
"product": 5,
"image_id": 6,
"title": "main foto"
}
}
]
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)
data = .. ваша структура ...
try:
product_image = next(filter(lambda x: 'ProductImage' in x.keys(), data))
except StopIteration:
product_image = None
if product_image:
# работаем дальше с product_image
product_image = list(filter(lambda x: 'ProductImage' in x.keys(), data))
Есть небольшая подсказка, сделать это с помощу eval().