django-rest将数据数组保存到db

时间:2018-05-13 08:49:29

标签: django django-rest-framework

我试图将表单数据保存到db中。  我为您提供了requset.data的打印件,因为您看到requirement有两件商品。

我想保存用于循环的数据库中的每个项目以保存列表中的每个项目,但循环将保存表格行中h-e-l,...项的每个字符... 哪里是我的错...谢谢

同时打印request.data.get('requirement')将重新调整第二项

这是在sever:

中打印request.data
<QueryDict: {'requirement': ['hello', 'bye'], 'audience': ['adasd'], 'achievement': ['asdasd'], 'section': ['410101010'], 'title': ['asdasd'], 'mini_description': ['asdad'], 'full_description': ['asdasd'], 'video_length': ['10101'], 'video_level': ['P'], 'price': [''], 'free': ['true'], 'image': [<InMemoryUploadedFile: p.gif (image/gif)>]}>

视图:

class StoreCreateAPIView(generics.CreateAPIView):
    parser_classes = (MultiPartParser, FormParser)
    permission_classes = [IsAuthenticated]

    def perform_create(self, serializer):
        serializer.save(author=self.request.user)

    def post(self, request, *args, **kwargs):
        if request.method == 'POST':
            print(request.data)
            file_serial = ProductSerializer(data=request.data, context={"request": request})
            if file_serial.is_valid():
                file_serial.save(author_id=request.user.id)
                requirement = request.data['requirement']
                audience = request.data.get('audience')
                achievement = request.data.get('achievement')
                sections = request.data.get('section')

                print(request.data['requirement'])
                pid = file_serial.data.get('product_id')
                for item in requirement :
                    req = ProductRequiredItems(
                        item = item,
                        product_id = pid
                    )
                    req.save()

1 个答案:

答案 0 :(得分:3)

首先,在您的代码中覆盖CreateAPIView的{​​{1}}方法会使您的自定义post方法失效,除非您在自定义的perform_create方法中明确地调用它。否则永远不会被召唤。

  

还打印request.data.get('requirement')将返回第二项

它会根据QueryDict.__getitem__(key)的Django文档返回最后一项。

  

我想保存用于循环的数据库中的每个项目以保存列表的每个项目,但循环将保存项目的每个字符,如h-e-l,...

这是因为post的上述功能。当你这样做时:

QueryDict

它将调用requirement = request.data['requirement'] # requirement = request.__getitem__('requirement') 方法,因此只返回最后一项(在您的示例中为字符串)。

<强>答案:

您可以简单地覆盖QueryDict.__getitem__(key)的{​​{1}}方法,让序列化程序处理所有其他方法。

CreateAPIView

看看DRF CreateModelMixin。它定义了create&amp;执行POST请求时CreateAPIView中使用的# views.py from django.shortcuts import render from rest_framework import generics, status from rest_framework.response import Response from .models import MyObj from .serializers import MyObjSerializer class MyObjView(generics.CreateAPIView): serializer_class = MyObjSerializer queryset = MyObj.objects.all() def create(self, request, *args, **kwargs): # The QueryDicts at request.POST and request.GET will be immutable # when accessed in a normal request/response cycle. # To get a mutable version you need to use QueryDict.copy(). req_data = request.data.copy() requirements = req_data.pop('requirement') serializers_data = [] for requirement in requirements: req_data ['requirement'] = requirement serializer = self.get_serializer(data=req_data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) serializers_data.append(serializer.data) return Response(serializers_data, status=status.HTTP_201_CREATED) # serializers.py from rest_framework import serializers from .models import MyObj class MyObjSerializer(serializers.ModelSerializer): class Meta: model = MyObj fields = '__all__' 个方法。我只是略微改变它们以处理你的具体情况。

希望它有所帮助。