您如何创建Django rest框架ListCreateAPIView?

时间:2018-11-26 23:01:21

标签: python django django-rest-framework

我正在尝试实现使用drf将一批记录上载到数据库的功能。 这是我在api视图中的课程。

class BatchRecordModelViewSet(ListCreateAPIView):
    """
    This is an API view to insert a batch of item counts.
    """
    serializer_class = serializers.BatchRecordSerializer
    queryset = models.Record.objects.all()

    def create(self, request, *args, **kwargs):

        data = request.data
        some_data = request.user.profile.profile_id
        for rec in data:
            rec.update(some_data=some_data)

        serializer = self.get_serializer(data=data, many=True)
        if serializer.is_valid():
            serializer.save()
            headers = self.get_success_headers(serializer.data)
            return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
        else:
            return Response(status=status.HTTP_400_BAD_REQUEST)

这是我要导入的序列化器:

class BatchRecordSerializer(serializers.ModelSerializer):
    item = RecordSerializer(many=True)

    class Meta:
        model = models.Record
        fields = ('field1', 'field2', 'field3', etc...)

这是我的urls.py文件中的摘录:

from django.urls import include, path, re_path
from rest_framework import routers
from my_app.api import viewSet1, viewSet2, viewSet3


router = routers.DefaultRouter()

router.register(r'endpoint1', viewSet1.BatchRecordModelViewSet, base_name='endpoint1')
router.register(r'endpoint2', viewSet2.SomeOtherViewSet, base_name='endpoint2')
router.register(r'endpoint3', viewSet3.SomeOtherViewSet, base_name='endpoint3')


urlpatterns = [
    path('v1/', include(router.urls)),
]

端点2和3的URL正常工作,只是端点1不断给我带来问题。

0 个答案:

没有答案