1

I have following Serializer

class PersonSerializer(serializers.ModelSerializer):
   
    comments = serializers.SerializerMethodField('paginated_comments')
    images = ImageSerializer(source='image_set', many=True)

    class Meta:
        model = Person
        exclude = ('paid', 'status', 'register_date', 'paid_date')

    def paginated_comments(self, obj):
    
        page_size = self.context['request'].query_params.get('size') or 12
        paginator = Paginator(obj.comment_set.all(), page_size)
        page_number = self.context['request'].query_params.get('page') or 1
        comments = paginator.page(page_number)
        serializer = CommentSerializer(comments, many=True)

        return OrderedDict(
                [
                    ('count', len(serializer.data) if serializer.data else 0),
                    ('next', comments.has_next()),
                    ('previous', comments.has_previous()),
                    ('results', serializer.data)
                ]
            )

Which returns info about user

id": "718b309c-864d-4c26-a80e-2e744ac3102a",
"comments": {},
"images": [],
"name": "piwщ",
"city": "piwщ",

}

I want to add to result field is_admin:True if user is admin, but if not, i don't want to add this field to result

The expected output if user is admin:

{d": "718b309c-864d-4c26-a80e-2e744ac3102a",
    "comments": {},
    "images": [],
    "name": "piwщ",
    "city": "piwщ",
    "is_admin": True
   }

The expected output if user is not admin:

{d": "718b309c-864d-4c26-a80e-2e744ac3102a",
    "comments": {},
    "images": [],
    "name": "piwщ",
    "city": "piwщ",
   }
Akash
  • 117
  • 8
Alex Nikitin
  • 841
  • 1
  • 10
  • 29
  • What is your expected output? – Preeti Y. Jan 12 '21 at 10:44
  • 3
    You can achieve that by overriding your serializer init method, but i would not recommend that. Just add is_admin:True/False all the time and make sure to mark this field read_only for security. This will answer your question though https://stackoverflow.com/questions/23643204/django-rest-framework-dynamically-return-subset-of-fields – Guillaume Jan 12 '21 at 10:49
  • @AlexNikitin You can try setting it null in case of non-admin using serializer method field and filter null values before returning the response. – Priyanshu Jain Jan 12 '21 at 14:10

0 Answers0