Ошибка "Недопустимое значение." при использовании сериализатора django rest framework Serializer

Я пытаюсь сохранить некоторую информацию из файла csv в DB с помощью django rest framework, в настоящее время я не уверен, где проблема, в представлении или в модели, для проверки я отправляю данные по мере их поступления в сериализатор. Вот мой view.py

import re
import csv
import codecs
import pandas as pd
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from django.shortcuts import render
from rest_framework.decorators import api_view

# Create your views here.
from rest_framework import viewsets,status
from .serializer import tripSerializer #,DataSourceSerializer
from .models import Trips
from rest_framework.response import Response


class TripViewSet(viewsets.ViewSet):
    def list(self, request):
        queryset = Trips.objects.all()
        serializer = tripSerializer(queryset, many=True)
        return Response(serializer.data)
    
    def insert(self, request):
        
        
        file=codecs.EncodedFile(request.FILES.get("file").open(),"utf-8")
        print(type(file))
        reader = pd.read_csv(file, delimiter=";")
        reader.columns = ['region','origin_coord','destination_coord','datetime','datasource'];
        
        
        reader=reader.to_dict(orient = 'records')[0]
        print("--------------------------------------------------------")
        print("DATA inicial",reader)
        print("--------------------------------------------------------")

        data={'region': 'Prague', 'origin_coord': 'POINT (14.4973794438195 50.00136875782316)', 'destination_coord': 'POINT (14.43109483523328 50.04052930943246)', 'datetime': '28/05/2018 9:03', 'datasource': 'funny_car'}
        serializer = tripSerializer(data=reader)
        print("trying to validate")
        if serializer.is_valid():
            serializer.save()
            return Response({"status":"success"}, status=status.HTTP_200_OK)
        else:
            return Response({"status":"Error!!","data":serializer.data,"Error:":serializer.errors,"message_error":serializer.error_messages}, status=status.HTTP_400_BAD_REQUEST)
    

Serializer.py

from django.shortcuts import render

# Create your views here.
from dataclasses import field, fields
from rest_framework import serializers
from .models import Datasources, Regions, Trips

        
class tripSerializer(serializers.ModelSerializer):
    
    
    region = serializers.SlugRelatedField(many=False,slug_field='regions_trips',queryset=Regions.objects.all())
    datasource = serializers.SlugRelatedField(many=False,slug_field='dataSource_trips',queryset=Datasources.objects.all())
       
    class Meta:
        model = Trips
        fields = ('origin_coord','destination_coord','datetime','datasource','region')
        
    
    def create(self, validated_data):
        
        print("validated_data:",validated_data)
        dataSource_trips = validated_data.pop('datasource')
        regions_trips = validated_data.pop('region')       
        
        datasourceCreated,created=Datasources.objects.get_or_create(**dataSource_trips)
        regionsCreated,created=Regions.objects.get_or_create(**regions_trips)   
        print("datasourceCreated.datasource",datasourceCreated.datasource)
        
        tripsCreated=Trips.objects.create(datasource=datasourceCreated,region=regionsCreated,**validated_data)
        
        return tripsCreated     

models.py

from asyncio.windows_events import NULL
from django.db import models

# Create your models here.
import datetime
from django.db.models.deletion import CASCADE


class Regions(models.Model):
    #cod_region = models.ForeignKey(Trips, related_name="Regions",on_delete=CASCADE)
    region     = models.CharField(null=False,max_length=1000)
    
    
class Datasources(models.Model):
    #cod_datasoruce = models.ForeignKey(Trips, related_name="Datasources",on_delete=CASCADE)
    datasource = models.CharField(null=False,max_length=1000)
    
    
class Trips(models.Model):
    region            = models.ForeignKey(Regions, related_name="regions_trips",on_delete=CASCADE)
    origin_coord      = models.CharField(null=False,max_length=1000)
    destination_coord = models.CharField(null=False,max_length=1000)
    datetime          = models.DateTimeField()
    datasource        = models.ForeignKey(Datasources, related_name="dataSource_trips", on_delete=CASCADE)
                                                                     
    
    

Как только я отправляю некоторые данные через Postman или даже данные, которые жестко закодированы в файле views.py, я получаю следующую ошибку: Я печатаю все поля, похожие на "error", пытаясь найти больше информации об ошибке.

{
"status": "Error!!",
"data": {
    "origin_coord": "POINT (14.4973794438195 50.00136875782316)",
    "destination_coord": "POINT (14.43109483523328 50.04052930943246)",
    "datetime": "28/05/2018 9:03",
    "datasource": "funny_car",
    "region": "Prague"
},
"Error:": {
    "datasource": [
        "Invalid value."
    ],
    "region": [
        "Invalid value."
    ]
},
"message_error": {
    "required": "This field is required.",
    "null": "This field may not be null.",
    "invalid": "Invalid data. Expected a dictionary, but got {datatype}."
}

}

Обновление:

Чтобы дать вам немного больше деталей, я добавил несколько отпечатков в код и поделился выводом в консоли, проблема es во время валидации сериализованного объекта.

Выход:

--------------------------------------------------------
DATA inicial {'region': 'Prague', 'origin_coord': 'POINT (14.4973794438195 50.00136875782316)', 'destination_coord': 'POINT (14.43109483523328 50.04052930943246)', 'datetime': '28/05/2018 9:03', 'datasource': 'funny_car'}
--------------------------------------------------------
trying to validate
Bad Request: /trips/Insert
[26/Jul/2022 17:54:59] ←[31;1m"POST /trips/Insert HTTP/1.1" 400 459←[0m

Я буду очень признателен за вашу помощь в этом вопросе.

Большое спасибо!

Вернуться на верх