I am looking a way for insert a parameter in a data serializer before save, 
I have a model with only 2 fields, for stay easy, let's consider that both 
are of an API service on the internet, like twitter. For example.

I have to accept a command line, via curl, like this:
curl -X POST -F twitter_id=1399 http://localhost:8000/api/users/, then to 
consult the api service and, finally, save on my database.

My problem is: There is just one parameter (twitter_id) on the query, how 
to insert a second parameter (twitter_name)?

Below I show my code and my try (commented)

model:
    class User(models.Model):
        twitter_id
        twitter_name 

view.py:

    class UserViewSet(viewsets.ModelViewSet):
        serializer_class = UserSerializer
        queryset = User.objects.all()

        def get_queryset(self):
            queryset = User.objects.all()
            twt_id = self.request.query_params.get('twitter_id', None)
            limit = self.request.query_params.get('limit', None)
    
            if tw_id is not None:
                queryset = queryset.filter(twitter_id=tw_id)
            elif limit is not None:        
                queryset = queryset[:int(limit)]
            return queryset
    
serializer.py

    class UserSerializer(serializers.ModelSerializer):
        links = serializers.SerializerMethodField()
        data_twt = {}
        
        class Meta:
            model = user
            fields = ('twitter_id', 'twitter_name')
    
         # ... 
   
        def get_links(self, obj):
            request = self.context['request']
            links = {'self': reverse('person-detail', kwargs={'pk': 
obj.pk}, request=request)}

        def validate(self, data):
            if bool(self.context['request'].POST):
                tw_id = str(data['twitter_id'])
                _tw_id = User.objects.filter(twitter_id=fb_id)
                if _tw_id.exists():
                    raise serializers.ValidationError('User already 
registered')
                else:
                    try:
                        self.data_twt = get_twitter_person(fb_id)
                        # Here I tried to modify data, but data is read only
                        # data['twitter_name'] = self.data_twt['name']
                    except:
                        raise serializers.ValidationError('Id not in 
Twitter')
            return data


-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to