How to show different data through one API in django-rest?

Viewed 118

#serializer.py file

class StorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Story
        fields = ("id",
            "title",
            "featured",
             summary",)

#views.py file

class StoryList(BaseListAPIView):
    serializer_class = StorySerializer
    model = Story

#url

url(r"^stories/org/", StoryList.as_view(), name="api.v1.org_story_list"),

when i will call api suppose api.v1.org_story_list then show all fields data id,title,fetured,summary. but when I will call same api but add extra parameter like that api.v1.org_story_list/addd then show specific field like that id,title,summary. featured field will not called.

How to do it ?

1 Answers

You can update your views and make custom list api view like this following code:

 def get(self, request, *args, **kwargs):
        data = UserSerializer(request.user).data
        if data=="xxxx":
            organizations = OrganizationUser.objects.filter(user=self.request.user).values('organization')
            data['organization_profiles'] = OrganizationProfileListSerializer(
                OrganizationProfile.objects.all(), many=True).data
        else: 
            data['organization_profiles'] = OrganizationProfileIndividualSerializer(
            OrganizationProfile.objects.get(user=request.user )).data

        return Response(data=data)

Here different serializer is being used based on condition.

Related