2

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Neat, thanks for this explanation and sample code. Would it also be feasible to do this recursively for nested objects?
Yup, tho again you'd need to deal with that logic yourself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.