Django REST Framework and nested resources (url)?

Want to make API with the following structure:
/user - user data
/user/companies - list of companies of the user
/user/companies/1 - specific company
/user/companies/1/contacts - contact list company
/user/companies/1/contacts/2 - specific contact

Want to do on the ViewSet, but faced with the fact that you have to override the methods to "traverse" company_id.
class PhotosViewSet(viewsets.ModelViewSet):
 serializer_class = serializers.CompanyPhotoSerializer
 queryset = models.CompanyPhoto.objects.all()
 permission_classes = [permissions.IsOwnerOrReadOnly]

 def list(self, request, *args, **kwargs):
 queryset = self.a queryset.filter(company_id=kwargs['company_id'])
 serializer = self.serializer_class(queryset, many=True)
 return response.Response(

 def retrieve(self, request, *args, **kwargs):
 queryset = self.a queryset.filter(company_id=kwargs['company_id'])\
 serializer = self.serializer_class(queryset)
 return response.Response(

So therefore I have to rewrite most of Musatov and their methods. And there's a normal view function easier to use. Tell me how this can be done more elegant? Will consider all options, including CBV and so on.

Read about lookup_url_kwarg in Generic views, but waiting for more options.
June 14th 19 at 20:37
2 answers
June 14th 19 at 20:39
Happiness rolled in the form of method overriding get_queryset, so viewset works as it should:
class PhotosViewSet(viewsets.ModelViewSet):
 serializer_class = serializers.CompanyPhotoSerializer
 permission_classes = [permissions.IsOwnerOrReadOnly]

 def get_queryset(self):
 company = self.kwargs.get('company_id')
 photos = models.CompanyPhoto.objects.filter(company_id=company)
 return photos

Even easier to live when so:
class ParentIDMixin:
 parent_field = "
 model = None

 def get_queryset(self, *args, **kwargs):
 queryset = self.model.objects.filter(**self._get_filter_key())
 return a queryset

 def _get_filter_key(self):
 parent_id = self.kwargs.get(self.parent_field)
 return {self.parent_field: parent_id}

class PhotosViewSet(ParentIDMixin, viewsets.ModelViewSet):
 serializer_class = serializers.CompanyPhotoSerializer
 permission_classes = [permissions.IsOwnerOrReadOnly]
 model = models.CompanyPhoto
 parent_field = 'company_id'
The documentation discusses a similar case, and there are links to the packages. You can read here and here. - Letha_Kuhn commented on June 14th 19 at 20:42
June 14th 19 at 20:41
Read on the topic of embedded URLs:

In my opinion, the attached URLs are harder to maintain, so we try to keep the structure as flat as possible.

Find more questions by tags APIDjangoRESTful API