I am using Django REST Framework and I found myself in the following situation: I have two APIViews that are identical to one another except for the ordering of the objects they return:
# Route: "/new"
class NewView(APIView):
"""
Returns JSON or HTML representations of "new" definitions.
"""
renderer_classes = [JSONRenderer, TemplateHTMLRenderer]
def get(self, request):
# Queryset
definitions = Definition.objects.filter(language=get_language())
definitions = definitions.order_by("-pub_date")
# HTML
if request.accepted_renderer.format == "html":
context = {}
context["definitions"] = definitions
context["tags"] = get_tags(definitions)
return Response(context, template_name="dictionary/index.html")
# JSON
serializer = DefinitionSerializer(definitions, many=True)
return Response(serializer.data)
# Route: "/random"
class RandomView(APIView):
"""
Returns JSON or HTML representations of "random" definitions.
"""
renderer_classes = [JSONRenderer, TemplateHTMLRenderer]
def get(self, request):
# Queryset
definitions = Definition.objects.filter(language=get_language())
definitions = definitions.order_by("?")
# HTML
if request.accepted_renderer.format == "html":
context = {}
context["definitions"] = definitions
context["tags"] = get_tags(definitions)
return Response(context, template_name="dictionary/index.html")
# JSON
serializer = DefinitionSerializer(definitions, many=True)
return Response(serializer.data)
As you can see, the only line that changes between these two views is the one that orders the Definition objects. How can I create a parent view to contain the shared code and a child view to sort objects?