如何在一个API视图中实现创建和更新?

时间:2019-10-11 13:16:45

标签: django django-rest-framework

我有一个名为 CarDetailsAdd VehicleDetails (字段-描述)的模型,VehicleDetails是 CarDetailsAdd 外键 >。我在此序列化程序中使用嵌套关系。使用此更新功能,我可以更新现有的车辆详细信息。根据UI,添加和更新在同一屏幕上运行。如果用户已更新该字段,则应对其进行更新,或者用户已添加新字段,则应添加它。如果用户同时更新和添加该怎么办??

(UI image)

# Serializer

class CarDetailsSerializer(serializers.ModelSerializer):
    vehicle_details = VehicleDetailsSerializer(many=True)

    class Meta:
        model = CarDetailsAdd
        fields = (
            'id', 'name', 'year', 'color', 'fuel_type',
            'vehicle_details',
        )
        read_only_fields = ['id']

    def update(self, instance, validated_data):

        vehicle_data = validated_data.pop('vehicle_details')

        vehicle = (instance.vehicle_details).all()

        vehicle = list(vehicle)

        instance.name = validated_data.get('name', instance.name)
        instance.year = validated_data.get('year', instance.year)
        instance.color = validated_data.get('color', instance.color)
        instance.fuel_type = validated_data.get('fuel_type', instance.fuel_type)
        instance.save()

        for vehicle_data in vehicle_data:
            vehicle = vehicle.pop(0)
            vehicle.description = vehicle_data.get('description', vehicle.description)
            vehicle.save()

        return instance

# View

class CarDetailsView(APIView):
    permission_classes = [IsAuthenticated]

    def put(self, request, pk, format=None):
        try:
            car = self.get_object(pk)
            serializer = CarDetailsSerializer(car, data=request.data)
            if serializer.is_valid():
                serializer.save()
                return Response({'response': 'Update Success', 'result': serializer.data})
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        except:
            return Response({'response': 'Oops! Something Went Wrong'}, status=status.HTTP_400_BAD_REQUEST)

0 个答案:

没有答案