Обновление или создание из файла CSV в Django

Я создал вот это, которое позволяет добавить несколько растений благодаря CSV-файлу :

class UploadFileView(generics.CreateAPIView):
    serializer_class = FileUploadSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        file = serializer.validated_data['file']
        reader = pd.read_csv(file)
        for _, row in reader.iterrows():
            new_file = Plant(
                name=row['Name'],
                plant_description=row["Plant description"],
                family=Family.objects.get(name=row['Family']),
                category=PlantCategory.objects.get(name=row['Category']),
                facility_rate=row["Facility rate"],
                seedling_depth=row['Seedling depth'],
                seedling_distance=row["Seedling distance"],
                row_spacing=row['Row spacing'],
                sunshine_index=row["Sunshine index"],
                irrigation_index=row["Irrigation index"],
                soil_nature=row['Soil nature'],
                soil_type=row["Soil type"],
                fertilizer_type=row['Fertilizer type'],
                acidity_index=row["Acidity index"],
                days_before_sprouting=row["Days before sprouting"],
                average_harvest_time=row['Average harvest time'],
                soil_depth=row["Soil depth"],
                plant_height=row['Plant height'],
                suitable_for_indoor_growing=row["Suitable for indoor growing"],
                suitable_for_outdoor_growing=row["Suitable for outdoor growing"],
                suitable_for_pot_culture=row['Suitable for pot culture'],
                hardiness_index=row["Hardiness index"],
                no_of_plants_per_meter=row['No of plants per meter'],
                no_of_plants_per_square_meter=row["No of plants per square meter"],
                min_temperature=row["Min temperature"],
                max_temperature=row['Max temperature'],
                time_to_transplant=row["Time to transplant"],
            )
            new_file.save()
        return Response({"status": "Success : plant(s) created"},
                        status.HTTP_201_CREATED)

Проблема в том, что если растения уже созданы, то появляется сообщение об ошибке, но я хотел бы убедиться, что если растение не создано, то мы его создали, иначе мы обновляем его новыми данными из CSV файла.

Я видел, что в Django есть метод update_or_create(), но не смог реализовать его в своем коде.

Если кто-то может мне помочь, было бы здорово!

здесь ты

class UploadFileView(generics.CreateAPIView):
    serializer_class = FileUploadSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        file = serializer.validated_data['file']
        reader = pd.read_csv(file)
        for _, row in reader.iterrows():
            Plant.objects.update_or_create(
                name=row['Name'],
                plant_description=row["Plant description"],
                family=Family.objects.get(name=row['Family']),
                category=PlantCategory.objects.get(name=row['Category']),
                facility_rate=row["Facility rate"],
                seedling_depth=row['Seedling depth'],
                seedling_distance=row["Seedling distance"],
                row_spacing=row['Row spacing'],
                sunshine_index=row["Sunshine index"],
                irrigation_index=row["Irrigation index"],
                soil_nature=row['Soil nature'],
                soil_type=row["Soil type"],
                fertilizer_type=row['Fertilizer type'],
                acidity_index=row["Acidity index"],
                days_before_sprouting=row["Days before sprouting"],
                average_harvest_time=row['Average harvest time'],
                soil_depth=row["Soil depth"],
                plant_height=row['Plant height'],
                suitable_for_indoor_growing=row["Suitable for indoor growing"],
                suitable_for_outdoor_growing=row["Suitable for outdoor growing"],
                suitable_for_pot_culture=row['Suitable for pot culture'],
                hardiness_index=row["Hardiness index"],
                no_of_plants_per_meter=row['No of plants per meter'],
                no_of_plants_per_square_meter=row["No of plants per square meter"],
                min_temperature=row["Min temperature"],
                max_temperature=row['Max temperature'],
                time_to_transplant=row["Time to transplant"],
            )
        return Response({"status": "Success : plant(s) created"},
                        status.HTTP_201_CREATED)
Вернуться на верх