HumphreyTriscuit February 2016

Overriding how a generic class based looks up an object from the URL arguments

My understanding is that generic class based views ultimately rely on a pk variable specified by the corresponding urls.py to perform a database lookup. In urls.py I specify the pk, then in the class-based view I just provide the queryset and serializer class.

Is there a way to keep the near DRY-ness of the generic view but override only how the class goes from a pk to an object or queryset? I know I could inherit from an APIView instead and provide the get, post, etc. methods myself, but then that's an awful lot more code. I want to keep using the inbuilt functionality of generics but just provide the mechanism to go from url arguments to an object or queryset.

I'm trying to allow objects to be specified in a url by their ordinality rather than their pk. So, /foo/1 maps to Foo.objects.all()[0].

Answers


HumphreyTriscuit February 2016

I think the solution is to override get_object - I hadn't realise I could access the url parameters under the view class itself:

class Foo(generics.RetrieveDestroyAPIView):
    serializer_class = FooSerializer

    def get_object(self):
        return Foo.objects.all()[self.kwargs['foo_if_in_url'] - 1]

Post Status

Asked in February 2016
Viewed 2,057 times
Voted 11
Answered 1 times

Search




Leave an answer