Iam嘗試使用Django Rest Framework批量創建某個表的行。我在documentation中看到DRF支持它。使用Django Rest Framework的ListSerializer批量創建
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}}
當我嘗試使用管理形式,我總是得到這個錯誤發佈。你能幫我確定我在這裏做錯了什麼嗎?
TypeError at /api/feed/ 'ProfileFeedItemListSerializer' object is not callable Request Method: GET Request URL: http://127.0.0.1:8080/api/feed/ Django Version: 1.11 Exception Type: TypeError Exception Value: 'ProfileFeedItemListSerializer' object is not callable Exception Location: /home/ubuntu/.virtualenvs/profiles_api/local/lib/python3.5/site-packages/rest_framework/generics.py in get_serializer, line 111 Python Executable: /home/ubuntu/.virtualenvs/profiles_api/bin/python Python Version: 3.5.2
Iam能夠發佈單個字典數據集,但發佈字典列表仍繼續拋出 ** AttributeError:'list'對象沒有屬性'get'** – Prasanna
我在答案中發現了錯字錯誤,嘗試了 –
when我傳遞了一個數據集列表,代碼流甚至沒有達到perform_create。它總是期望數據作爲字典傳遞。 必須有一種方法可以告訴DRF傳入數據是字典列表而不是單個字典。 – Prasanna