Last active
August 29, 2015 14:22
-
-
Save willstott101/f95efe3a381bcd2386fb to your computer and use it in GitHub Desktop.
Nested Lists endpoints within DRF viewsets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class NestedListMixin(object): | |
def get_nested_list(self, queryset, serializer_class): | |
""" | |
List view in function form. | |
First argument can be a list or a queryset. | |
""" | |
page = self.paginate_queryset(queryset) | |
if page is not None: | |
serializer = serializer_class(page, many=True, | |
context=self.get_serializer_context()) | |
return self.get_paginated_response(serializer.data) | |
serializer = serializer_class(queryset, many=True) | |
return Response(serializer.data) | |
def get_filtered_nested_list(self, queryset, serializer_class, extra_view_attributes=None): | |
""" | |
List view in function form. | |
First argument must be queryset for correct filtering. | |
""" | |
if extra_view_attributes is None: | |
extra_view_attributes = {} | |
extra_view_attributes.setdefault('serializer_class', serializer_class) | |
view_class = type('NestedView', (object,), extra_view_attributes) | |
# Usually defined in GenericAPIView.filter_queryset | |
# Re-written here to override the passed view. | |
for backend in list(self.filter_backends): | |
queryset = backend().filter_queryset(self.request, queryset, view_class()) | |
return self.get_nested_list(queryset, serializer_class) | |
# Usage: | |
class VendorViewSet(NestedListMixin, viewsets.ModelViewSet): | |
#... | |
@detail_route(methods=['get']) | |
def requirements(self, request, pk=None): | |
queryset = self.get_object().vendorrequirement_set.all() | |
return self.get_filtered_nested_list(queryset, serializers.VendorRequirementSerializer) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment