Jamie
Jamie

Reputation: 2291

Accessing serializer fields by url in Django Rest Framework

Setup

I have a standard setup with model Account and corresponding AccountSerializer.

serializers.py:

class AccountSerializer(serializers.ModelSerializer):
    class Meta:
        model = Account
        fields = ('id', 'account_name', 'users', 'created')

views.py:

class SingleAccountView(generics.RetrieveAPIView):
    serializer_class = AccountSerializer
    queryset = Account.objects.all()
    lookup_field = 'id'
    permission_classes = ()

urls.py:

url(r'^account/(?P<id>\w+)$', SingleAccountView.as_view())

Goal

I want to be able to access the properties of my serializer by url, without hardcoding them into urls.py. E.g., I want to be able to go to website.com/account/23/account_name to get the account name for account 23. How can I achieve this?

Upvotes: 2

Views: 691

Answers (1)

Tom Christie
Tom Christie

Reputation: 33901

You'll need to write a view explicitly to do that, as none of the generic views cover that use case.

Something along these lines would be about right...

class SingleAccountPropertyView(generics.GenericAPIView):
    lookup_field = 'id'

    def get(self, request, id, property_name):
        instance = self.get_object()
        if not hasattr(instance, property_name):
            return Response({'errors': 'no such property'}, status.HTTP_404_NOT_FOUND)
        return Response({'property': getattr(instance, property_name)}

You could also just use the regular APIView instead of GenericAPIView, in which case you'd want to write the instance lookup explicitly, instead of using the generic get_object()/lookup_field functionality that GenericAPIView provides.

Upvotes: 2

Related Questions