Django Rest Framework: Change Serializer or Add Field Based on Authentication










2















I have a viewset as follows:



class CardViewSet(viewsets.ReadOnlyModelViewSet):
"""
Standard Viewset for listing cards
"""
pagination_class = StandardCellSetPagination
permission_classes = [AllowAny, IsAuthenticated]

def list(self, request):
queryset = Card.objects.exclude(reply_to__isnull=False).order_by('-created')
cards = self.paginate_queryset(queryset)
serializer = CardCellSerializer(cards, many=True)
return self.get_paginated_response(serializer.data)

def retrieve(self, request, pk=None):
queryset = Card.objects.all()
card = get_object_or_404(queryset, pk=pk)
serializer = CardSerializer(card)
return Response(serializer.data)


My serializer for the CardSerializer is:



class CardSerializer(serializers.ModelSerializer):
class Meta:
model = Card


How do I either



  • Change the serializer for the retrieve method if the viewset has the permission IsAuthenticated?
    OR

  • Add a field to the CardSerializer if viewset has IsAuthenticated?

Such that I can return True / False if a user has favorited the card via a SerializerMethodField










share|improve this question
























  • What are trying to achieve with this?

    – Ivan
    Nov 1 '15 at 5:49











  • @Ivan If a user is authenticated I want the serializer to return if a user has favorited the card or not. This I was thinking of achieving via a SerializerMethodField

    – blue_zinc
    Nov 1 '15 at 5:54















2















I have a viewset as follows:



class CardViewSet(viewsets.ReadOnlyModelViewSet):
"""
Standard Viewset for listing cards
"""
pagination_class = StandardCellSetPagination
permission_classes = [AllowAny, IsAuthenticated]

def list(self, request):
queryset = Card.objects.exclude(reply_to__isnull=False).order_by('-created')
cards = self.paginate_queryset(queryset)
serializer = CardCellSerializer(cards, many=True)
return self.get_paginated_response(serializer.data)

def retrieve(self, request, pk=None):
queryset = Card.objects.all()
card = get_object_or_404(queryset, pk=pk)
serializer = CardSerializer(card)
return Response(serializer.data)


My serializer for the CardSerializer is:



class CardSerializer(serializers.ModelSerializer):
class Meta:
model = Card


How do I either



  • Change the serializer for the retrieve method if the viewset has the permission IsAuthenticated?
    OR

  • Add a field to the CardSerializer if viewset has IsAuthenticated?

Such that I can return True / False if a user has favorited the card via a SerializerMethodField










share|improve this question
























  • What are trying to achieve with this?

    – Ivan
    Nov 1 '15 at 5:49











  • @Ivan If a user is authenticated I want the serializer to return if a user has favorited the card or not. This I was thinking of achieving via a SerializerMethodField

    – blue_zinc
    Nov 1 '15 at 5:54













2












2








2








I have a viewset as follows:



class CardViewSet(viewsets.ReadOnlyModelViewSet):
"""
Standard Viewset for listing cards
"""
pagination_class = StandardCellSetPagination
permission_classes = [AllowAny, IsAuthenticated]

def list(self, request):
queryset = Card.objects.exclude(reply_to__isnull=False).order_by('-created')
cards = self.paginate_queryset(queryset)
serializer = CardCellSerializer(cards, many=True)
return self.get_paginated_response(serializer.data)

def retrieve(self, request, pk=None):
queryset = Card.objects.all()
card = get_object_or_404(queryset, pk=pk)
serializer = CardSerializer(card)
return Response(serializer.data)


My serializer for the CardSerializer is:



class CardSerializer(serializers.ModelSerializer):
class Meta:
model = Card


How do I either



  • Change the serializer for the retrieve method if the viewset has the permission IsAuthenticated?
    OR

  • Add a field to the CardSerializer if viewset has IsAuthenticated?

Such that I can return True / False if a user has favorited the card via a SerializerMethodField










share|improve this question
















I have a viewset as follows:



class CardViewSet(viewsets.ReadOnlyModelViewSet):
"""
Standard Viewset for listing cards
"""
pagination_class = StandardCellSetPagination
permission_classes = [AllowAny, IsAuthenticated]

def list(self, request):
queryset = Card.objects.exclude(reply_to__isnull=False).order_by('-created')
cards = self.paginate_queryset(queryset)
serializer = CardCellSerializer(cards, many=True)
return self.get_paginated_response(serializer.data)

def retrieve(self, request, pk=None):
queryset = Card.objects.all()
card = get_object_or_404(queryset, pk=pk)
serializer = CardSerializer(card)
return Response(serializer.data)


My serializer for the CardSerializer is:



class CardSerializer(serializers.ModelSerializer):
class Meta:
model = Card


How do I either



  • Change the serializer for the retrieve method if the viewset has the permission IsAuthenticated?
    OR

  • Add a field to the CardSerializer if viewset has IsAuthenticated?

Such that I can return True / False if a user has favorited the card via a SerializerMethodField







python django api django-rest-framework






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 1 '15 at 5:55







blue_zinc

















asked Nov 1 '15 at 5:26









blue_zincblue_zinc

86521327




86521327












  • What are trying to achieve with this?

    – Ivan
    Nov 1 '15 at 5:49











  • @Ivan If a user is authenticated I want the serializer to return if a user has favorited the card or not. This I was thinking of achieving via a SerializerMethodField

    – blue_zinc
    Nov 1 '15 at 5:54

















  • What are trying to achieve with this?

    – Ivan
    Nov 1 '15 at 5:49











  • @Ivan If a user is authenticated I want the serializer to return if a user has favorited the card or not. This I was thinking of achieving via a SerializerMethodField

    – blue_zinc
    Nov 1 '15 at 5:54
















What are trying to achieve with this?

– Ivan
Nov 1 '15 at 5:49





What are trying to achieve with this?

– Ivan
Nov 1 '15 at 5:49













@Ivan If a user is authenticated I want the serializer to return if a user has favorited the card or not. This I was thinking of achieving via a SerializerMethodField

– blue_zinc
Nov 1 '15 at 5:54





@Ivan If a user is authenticated I want the serializer to return if a user has favorited the card or not. This I was thinking of achieving via a SerializerMethodField

– blue_zinc
Nov 1 '15 at 5:54












1 Answer
1






active

oldest

votes


















6














You can do this:



def retrieve(self, request, pk=None):
queryset = Card.objects.all()
card = get_object_or_404(queryset, pk=pk)

# Same for list method
if request.user and request.user.is_authenticated:
serializer = AuthenticatedCardSerializer(card)
else:
serializer = CardSerializer(card)

return Response(serializer.data)


AuthenticatedCardSerializer could then extend CardSerializer to include any fields visible to authenticated users.



Also if you decide to use same serialization behavior for list and retrieve, you could override get_serializer_class in your viewset instead:



def get_serializer_class(self):
if self.request.user and self.request.user.is_authenticated:
return AuthenticatedCardSerializer
else:
return CardSerializer


and leave everything else to the default list/retrieve implementations.



As an alternative, you could add the field in serializer's __init__. You can get the request from the context kwarg, do the same check and add any fields you need. I think though that it is needlessly more complicated than just having two serializers.






share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f33459501%2fdjango-rest-framework-change-serializer-or-add-field-based-on-authentication%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    6














    You can do this:



    def retrieve(self, request, pk=None):
    queryset = Card.objects.all()
    card = get_object_or_404(queryset, pk=pk)

    # Same for list method
    if request.user and request.user.is_authenticated:
    serializer = AuthenticatedCardSerializer(card)
    else:
    serializer = CardSerializer(card)

    return Response(serializer.data)


    AuthenticatedCardSerializer could then extend CardSerializer to include any fields visible to authenticated users.



    Also if you decide to use same serialization behavior for list and retrieve, you could override get_serializer_class in your viewset instead:



    def get_serializer_class(self):
    if self.request.user and self.request.user.is_authenticated:
    return AuthenticatedCardSerializer
    else:
    return CardSerializer


    and leave everything else to the default list/retrieve implementations.



    As an alternative, you could add the field in serializer's __init__. You can get the request from the context kwarg, do the same check and add any fields you need. I think though that it is needlessly more complicated than just having two serializers.






    share|improve this answer





























      6














      You can do this:



      def retrieve(self, request, pk=None):
      queryset = Card.objects.all()
      card = get_object_or_404(queryset, pk=pk)

      # Same for list method
      if request.user and request.user.is_authenticated:
      serializer = AuthenticatedCardSerializer(card)
      else:
      serializer = CardSerializer(card)

      return Response(serializer.data)


      AuthenticatedCardSerializer could then extend CardSerializer to include any fields visible to authenticated users.



      Also if you decide to use same serialization behavior for list and retrieve, you could override get_serializer_class in your viewset instead:



      def get_serializer_class(self):
      if self.request.user and self.request.user.is_authenticated:
      return AuthenticatedCardSerializer
      else:
      return CardSerializer


      and leave everything else to the default list/retrieve implementations.



      As an alternative, you could add the field in serializer's __init__. You can get the request from the context kwarg, do the same check and add any fields you need. I think though that it is needlessly more complicated than just having two serializers.






      share|improve this answer



























        6












        6








        6







        You can do this:



        def retrieve(self, request, pk=None):
        queryset = Card.objects.all()
        card = get_object_or_404(queryset, pk=pk)

        # Same for list method
        if request.user and request.user.is_authenticated:
        serializer = AuthenticatedCardSerializer(card)
        else:
        serializer = CardSerializer(card)

        return Response(serializer.data)


        AuthenticatedCardSerializer could then extend CardSerializer to include any fields visible to authenticated users.



        Also if you decide to use same serialization behavior for list and retrieve, you could override get_serializer_class in your viewset instead:



        def get_serializer_class(self):
        if self.request.user and self.request.user.is_authenticated:
        return AuthenticatedCardSerializer
        else:
        return CardSerializer


        and leave everything else to the default list/retrieve implementations.



        As an alternative, you could add the field in serializer's __init__. You can get the request from the context kwarg, do the same check and add any fields you need. I think though that it is needlessly more complicated than just having two serializers.






        share|improve this answer















        You can do this:



        def retrieve(self, request, pk=None):
        queryset = Card.objects.all()
        card = get_object_or_404(queryset, pk=pk)

        # Same for list method
        if request.user and request.user.is_authenticated:
        serializer = AuthenticatedCardSerializer(card)
        else:
        serializer = CardSerializer(card)

        return Response(serializer.data)


        AuthenticatedCardSerializer could then extend CardSerializer to include any fields visible to authenticated users.



        Also if you decide to use same serialization behavior for list and retrieve, you could override get_serializer_class in your viewset instead:



        def get_serializer_class(self):
        if self.request.user and self.request.user.is_authenticated:
        return AuthenticatedCardSerializer
        else:
        return CardSerializer


        and leave everything else to the default list/retrieve implementations.



        As an alternative, you could add the field in serializer's __init__. You can get the request from the context kwarg, do the same check and add any fields you need. I think though that it is needlessly more complicated than just having two serializers.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 15 '18 at 4:24









        nos

        6,840145578




        6,840145578










        answered Nov 1 '15 at 6:39









        IvanIvan

        3,83521739




        3,83521739





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f33459501%2fdjango-rest-framework-change-serializer-or-add-field-based-on-authentication%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Use pre created SQLite database for Android project in kotlin

            Darth Vader #20

            Ondo