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(serializer.data)

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


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.

UPD:
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
Solution
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:
https://stackoverflow.com/questions/20951419/what-...
https://softwareengineering.stackexchange.com/ques...

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