J
J
Jekson2018-08-15 21:11:09
Django
Jekson, 2018-08-15 21:11:09

Django Rest Framework: how to add extra field to context?

I'm trying to display an additional field using SerializerMethodField, but I don't get the result in the output.

class SampleSerializer(serializers.HyperlinkedModelSerializer):
    ...
    ...
    new = serializers.SerializerMethodField()

    class Meta:
        model = Platform
    def get_new(self, obj):
        value = getattr(obj, 'new', False)
        return value

views.py
class MyAuthView(APIView):    
    permission_classes = (permissions.IsAuthenticated,)    
    def post(self, request, *args, **kwargs):
        .....
        some code
        .....

        try:
           ...some code...
           try:
              p = Platform.objects.get(
                content_type=ContentType.objects.get_for_model(y),
                object_id=y.id,
                user=request.user
            )
           except:
              p = Platform(user=request.user,
                         platform=y, description=description)
           new = False <------- новая переменная
        except Youtube.DoesNotExist:
           p = Platform(user=request.user,
                         platform=y, description=description)
           new = True    <------- новая переменная            
        return Response(
            PlatformSerializer(p, context={'request': request}).data
        )

Tell me what is missing?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Tikhonov, 2018-08-16
@Lepilov

`new` is a local variable of view, it does not get into the p object
p.new = True

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question