Coverage for apis_core/generic/api_views.py: 43%

21 statements  

« prev     ^ index     » next       coverage.py v7.6.4, created at 2024-11-22 07:51 +0000

1from rest_framework import viewsets 

2 

3from .filterbackends import GenericFilterBackend 

4from .helpers import first_member_match, makeclassprefix, module_paths 

5from .serializers import GenericHyperlinkedModelSerializer, serializer_factory 

6 

7 

8class ModelViewSet(viewsets.ModelViewSet): 

9 """ 

10 API ViewSet for a generic model. 

11 The queryset is overridden by the first match from 

12 the `first_member_match` helper. 

13 The serializer class is overridden by the first match from 

14 the `first_member_match` helper. 

15 """ 

16 

17 filter_backends = [GenericFilterBackend] 

18 

19 def dispatch(self, *args, **kwargs): 

20 self.model = kwargs.get("contenttype").model_class() 

21 return super().dispatch(*args, **kwargs) 

22 

23 def get_queryset(self): 

24 queryset_methods = module_paths( 

25 self.model, path="querysets", suffix="ViewSetQueryset" 

26 ) 

27 queryset = first_member_match(queryset_methods) or (lambda x: x) 

28 return queryset(self.model.objects.all()) 

29 

30 def get_serializer_class(self): 

31 renderer = getattr(getattr(self, "request", {}), "accepted_renderer", None) 

32 serializer_class_modules = module_paths( 

33 self.model, path="serializers", suffix="Serializer" 

34 ) 

35 if renderer is not None: 

36 prefix = makeclassprefix(renderer.format) 

37 serializer_class_modules = ( 

38 module_paths( 

39 self.model, path="serializers", suffix=f"{prefix}Serializer" 

40 ) 

41 + serializer_class_modules 

42 ) 

43 

44 serializer_class = first_member_match( 

45 serializer_class_modules, 

46 getattr(renderer, "serializer", GenericHyperlinkedModelSerializer), 

47 ) 

48 return serializer_factory(self.model, serializer=serializer_class)