django rest框架导入csv thorws要求Id错误

时间:2018-07-24 11:52:08

标签: ajax django-models django-rest-framework

我正在尝试为数据库中的现有表导入CSV。为此,我正在使用django-rest-framework-csv应用程序。虽然发生了事件,但我通过javascript传递了所有必需的数据,但出现了以下错误

OrderedDict([('id',[u'此字段必填。'])])

CSV格式

    address,city,id,zip
    sa,italy,4,99999
    sa,italy,5,8989
   sa,italy,6,99999
   sa,italy,7,8989

请查看Modelviewset,Serilizer和Model以获得更多详细信息

class AdressCSVViewSet(viewsets.ModelViewSet):
"""ViewSet for the Adress class"""

queryset = Adress.objects.all()
serializer_class = AdressCSVSerializer
parser_classes = (CSVParser,) + tuple(api_settings.DEFAULT_PARSER_CLASSES)
renderer_classes = (CSVRenderer,) + tuple(api_settings.DEFAULT_RENDERER_CLASSES)
permission_classes = [IsAuthenticated]


def get_renderer_context(self):
    context = super(AdressCSVViewSet, self).get_renderer_context()
    context['header'] = (
        self.request.GET['fields'].split(',')
        if 'fields' in self.request.GET else None)
    return context

@list_route(methods=['POST'])
def bulk_upload(self, request, *args, **kwargs):

    serializer = self.get_serializer(data=request.data, many=True)
    serializer.is_valid(raise_exception=True)
    return Response(serializer.data)
    serializer.save()
    return Response(serializer.data)


class CSVSerializer(serializers.ModelSerializer):
 class Meta:
     model = Adress
     fields = (

        'id',
        'address',
        'city',
        'zip'
     )

class Adress(models.Model):
    # Fields
    id = IntegerField(primary_key=True)
    address = CharField(max_length=500, blank=True, null=True)
    city = CharField(max_length=500, blank=True, null=True)
    zip = CharField(max_length=500, blank=True, null=True)

请求数据:

  [{u'city': u'italy', u'id': u'4', u'zip': u'99999', u'address': u'sa'}, {u'city': u'italy', u'id': u'5', u'zip': u'8989', u'address': u'sa'}, {u'city': u'italy', u'id': u'6', u'zip': u'99999', u'address': u'sa'}, {u'city': u'italy', u'id': u'7', u'zip': u'8989', u'address': u'sa'}]

0 个答案:

没有答案