使用Django Rest Framework的ListSerializer批量创建

时间:2017-08-28 11:13:55

标签: django

我尝试使用Django Rest Framework为某个表批量创建行。我在documentation中看到DRF支持它。

views.py

class UserProfileFeedViewSet(viewsets.ModelViewSet):
    """Handles creating, reading and updating profile feed items."""

    authentication_classes = (TokenAuthentication,)
    queryset = models.ProfileFeedItem.objects.all()
    serializer_class = serializers.ProfileFeedItemSerializer(queryset, many=True)
    permission_classes = (permissions.PostOwnStatus, IsAuthenticated)

    def perform_create(self, serializer):
        """Sets the user profile to the logged in user."""

        serializer.save(user_profile=self.request.user)

serializers.py

class ProfileFeedItemListSerializer(serializers.ListSerializer):
   def create(self,validated_data):
       feed_list = [ProfileFeedItem(**item) for item in validated_data]
       return ProfileFeedItem.objects.bulk_create(feed_list)

class ProfileFeedItemSerializer(serializers.ModelSerializer):
    """A serializer for profile feed items."""

    class Meta:
        model = models.ProfileFeedItem
        list_serializer_class = ProfileFeedItemListSerializer
        fields = ('id', 'user_profile', 'status_text', 'created_on')
        extra_kwargs = {'user_profile': {'read_only': True}}

当我尝试使用管理表单发布时,我总是会收到此错误。能否请你帮我确定我在这里做错了什么?

  

/ api / feed /'ProfileFeedItemListSerializer'对象中的TypeError不是   可调用请求方法:GET请求   URL:http://127.0.0.1:8080/api/feed/ Django版本:1.11例外   类型:TypeError异常值:'ProfileFeedItemListSerializer'   object不可调用Exception   位置:/home/ubuntu/.virtualenvs/profiles_api/local/lib/python3.5/site-packages/rest_framework/generics.py   在get_serializer中,第111行Python   可执行文件:/home/ubuntu/.virtualenvs/profiles_api/bin/python Python   版本:3.5.2

2 个答案:

答案 0 :(得分:3)

试一试:

def create(self, request, *args, **kwargs):
    many = isinstance(request.data, list)
    serializer = self.get_serializer(data=request.data, many=many)
    serializer.is_valid(raise_exception=True)
    self.perform_create(serializer)
    headers = self.get_success_headers(serializer.data)
    return Response(serializer.data, headers=headers)

def perform_create(self, serializer):
    if type(serializer.validated_data) == list:
         for item in serializer.validated_data:
              item.update({'user_profile': self.request.user})
    else:
        serializer.validated_data.update({'user_profile': self.request.user})
    serializer.save()

不幸的是现在我无法检查解决方案,但也许它会给出正确的方法

答案 1 :(得分:1)

Serializer_class应该是类,而不是类实例。尝试更改此

serializer_class = serializers.ProfileFeedItemSerializer(queryset, many=True)

到此:

serializers.ProfileFeedItemSerializer