3

Iam trying to bulk create rows for a certain table using Django Rest Framework. I see in the documentation that DRF supports it.

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}}

When i try posting using admin form i always get this error. Can you please help me identify what am i doing wrong here ?

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

2 Answers 2

8

try it:

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()

unfortunately now I can't check the solution, but maybe it will give right way

Sign up to request clarification or add additional context in comments.

9 Comments

Iam able to post single dictionary datasets with this but posting list of dictionaries continues to throw AttributeError: 'list' object has no attribute 'get'
when i pass a list of dataset the code flow does not even reach perform_create. It always expects the data to be passed as a dictionary. There must be a way to tell DRF that the incoming data is a list of dictionaries and not a single dictionary.
added the create method
Awesome...that created the multiple rows for passed dataset. But the AttributeError: 'list' object has no attribute 'get' trace still shows up in console..How do i suppress it ?
The AttributeError occurs only while i post from Django Admin form. It does not occur while posting via postman.
|
1

Serializer_class should be class, not class instance. Try to change this

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

to this:

serializers.ProfileFeedItemSerializer

6 Comments

I changed that. Iam trying to post the following dataset: [{ "status_text": "Hello" },{ "status_text": "World" } ] Now when i submit the form i see following error in console: AttributeError: 'list' object has no attribute 'get'
@Prasanna can you add full error text to the question?
@Prasanna try to add serializer = self.get_serializer(data=self.request.data, many=True) before serializer.save(user_profile=self.request.user) line in UserProfileFeedViewSet
Added the get_serializer but still the same error as full trace above...
@Prasanna I changed my comment, did you try it?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.