'Django. How to save serialized and validated data?

I have a Car model with name, model and serial number fields. In which the combination of the name and model fields must be unique.

I am using serializers.ModelSerializer from rest_framework and validator UniqueTogetherValidator.

    validators = [
        UniqueTogetherValidator(
            queryset=models.Car.objects.all(),
            fields=['name', 'model']
        )
    ]

The database already has an entry {'name': 'one', 'model': '13', 'serial number': 99}.

I want to add a list of cars:

    data = [{'name': 'one', 'model': '13', 'serial number': 99},   {'name': 'two', 'model': '3', 'serial number ': 98},   {' name ':' three ',' model ':' 1 ',' serial number ': 949}]

For this I use:

serializer = CarSerializer (data = data)

if serializer.is_valid ():
     serializer.save ()

I understand that is_valid () will return false.



Solution 1:[1]

for item in data:
    serializer = CarSerializer (data = item)

    if serializer.is_valid ():
        serializer.save ()

Or if you don't want to do lots of queries:

    valid_data = []
    for item in data:
        serializer = CarSerializer (data = item)
        if serializer.is_valid():
            valid_data.append(item)

    valid_data_serializer = CarSerializer (data = valid_data)
    if valid_data_serializer.is_valid ():
        valid_data_serializer.save ()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1