P
P
PyCi2021-11-30 14:00:41
Python
PyCi, 2021-11-30 14:00:41

How to process a list of dictionaries?

I get a list of dictionaries and I want to sort them out and send them to the correct model for the database:

[
  {
    "AttributeName": {
      "id": 1,
      "title": "color"
    }
  },
  {
    "AttributeValue": {
      "id": 1,
      "value": "red"
    }
  },
  {
    "ProductImage": {
      "id": 5,
      "product": 5,
      "image_id": 6,
      "title": "main foto"
    }
  }
]

I thought to solve it through a loop and iterate using if , but I ran into a KeyError and thought that this was far from the right option. There is a little hint to do this with eval() .

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
PyCi, 2021-12-11
@PyCi

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)

V
Vladimir Kuts, 2021-11-30
@fox_12

So what's the problem?

data = .. ваша структура ...
try:
    product_image = next(filter(lambda x: 'ProductImage' in x.keys(), data))
except StopIteration:
    product_image = None

if product_image:
    # работаем дальше с product_image

if multiple values ​​can be - then a list of product images:
product_image = list(filter(lambda x: 'ProductImage' in x.keys(), data))

There is a little hint to do this with eval().

some nonsense was suggested ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question