我们从Python开源项目中,提取了以下9个代码示例,用于说明如何使用rest_framework.viewsets.ModelViewSet()。
def test_default_serializer(self): if StrictVersion(VERSION) >= StrictVersion('3.0.0'): return from rest_framework.viewsets import ModelViewSet from django.http import HttpRequest from testapp.models import TestModel class TestViewSet(ModelViewSet): model = TestModel view = TestViewSet() view.request = HttpRequest() si = SerializerIntrospector(view.get_serializer_class()) self.assertEqual(si.name, 'TestModelSerializer')
def setUp(self): class NoteViewSet(viewsets.ModelViewSet): queryset = RouterTestModel.objects.all() self.router = DefaultRouter() self.router.root_view_name = 'nameable-root' self.router.register(r'notes', NoteViewSet) self.urls = self.router.urls
def test_get_base_viewset(self): class DummyViewSet(ModelViewSet): pass class OtherDummyViewSet(ModelViewSet): pass class DummyEndpoint(Endpoint): model = Product base_viewset = DummyViewSet class DummyReadOnlyEndpoint(DummyEndpoint): read_only = True class OtherDummyReadOnlyEndpoint(Endpoint): model = Product read_only = True base_viewset = OtherDummyViewSet base_readonly_viewset = DummyViewSet dummy = DummyEndpoint() self.assertTrue(issubclass(dummy.get_base_viewset(), DummyViewSet)) dummy = DummyReadOnlyEndpoint() self.assertTrue(issubclass(dummy.get_base_viewset(), DummyViewSet)) dummy = OtherDummyReadOnlyEndpoint() self.assertTrue(issubclass(dummy.get_base_viewset(), DummyViewSet))
def _rest_endpoint(cls): from rest_framework import viewsets viewset = type('Viewset', (viewsets.ModelViewSet,), {'queryset': cls._rest_queryset(), 'serializer_class': cls._rest_serializer(), '__doc__': cls.__doc__, }) name = getattr(cls.Rest, 'name', getattr(cls.Meta, 'verbose_name_plural', cls.__name__)) route = getattr(cls.Rest, 'route', name).lower() viewset.__name__ = name return (r'{}'.format(route), viewset, route)
def setUp(self): Group.objects.bulk_create([Group(name=name) for name in ['group1', 'group2', 'group3']]) class GroupSerializer(ModelSerializer): class Meta: model = Group fields = '__all__' class GroupViewSet(ModelViewSet): queryset = Group.objects.all() serializer_class = GroupSerializer permission_classes = [DjangoObjectPermissions] filter_backends = [ChemoPermissionsFilter] self.user = User.objects.create_user(username='testuser', password='test123.') self.perm = Permission.objects.create(content_type=get_content_type(Group), name='Can view group', codename='view_group') self.access_rule = AccessRule.objects.create(ctype_source=get_content_type(User), ctype_target=get_content_type(Group), is_active=True, relation_types=[{'GROUPS': None}]) self.view = GroupViewSet self.patched_settings = modify_settings( AUTHENTICATION_BACKENDS={'append': self.backend} ) self.patched_settings.enable()
def get_queryset(self): user_id = self.kwargs['userid'] sorting = self.request.query_params.get('sorting', None) if sorting == 'upvotes': return Comment.sorted_objects.upvotes().filter(author=user_id) elif sorting == 'newest': return Comment.sorted_objects.newest().filter(author=user_id) else: return Comment.sorted_objects.upvotes().filter(author=user_id) # class PostUpvoteViewSet(viewsets.ModelViewSet): # queryset = PostUpvote.objects.all() # serializer_class = PostUpvoteSerializer # # def get_permissions(self): # if self.request.method in permissions.SAFE_METHODS: # return (permissions.AllowAny(),) # return (permissions.IsAuthenticated(), IsOwner(),) # # def perform_create(self, serializer): # instance = serializer.save(voter=self.request.user) # return super(PostUpvoteViewSet, self).perform_create(serializer) # # # class CommentUpvoteViewSet(viewsets.ModelViewSet): # queryset = PostUpvote.objects.all() # serializer_class = CommentUpvoteSerializer # # def get_permissions(self): # if self.request.method in permissions.SAFE_METHODS: # return (permissions.AllowAny(),) # return (permissions.IsAuthenticated(), IsOwner(),) # # def perform_create(self, serializer): # instance = serializer.save(voter=self.request.user) # return super(PostUpvoteViewSet, self).perform_create(serializer)
def test_format_api_patterns_url_import_with_routers(self): class MockApiViewSet(ModelViewSet): serializer_class = CommentSerializer model = User queryset = User.objects.all() class AnotherMockApiViewSet(ModelViewSet): serializer_class = CommentSerializer model = User queryset = User.objects.all() router = DefaultRouter() router.register(r'other_views', MockApiViewSet, base_name='test_base_name') router.register(r'more_views', AnotherMockApiViewSet, base_name='test_base_name') urls_app = patterns('', url(r'^', include(router.urls))) urls = patterns( '', url(r'api/', include(urls_app)), url(r'test/', include(urls_app)) ) apis = self.urlparser.get_apis(urls) self.assertEqual( 4, sum(api['path'].find('api') != -1 for api in apis)) self.assertEqual( 4, sum(api['path'].find('test') != -1 for api in apis))
def test_exclude_router_api_root(self): class MyViewSet(ModelViewSet): serializer_class = CommentSerializer queryset = User.objects.all() model = User router = DefaultRouter() router.register('test', MyViewSet, base_name='test_base_name') urls_created = len(router.urls) apis = self.urlparser.get_apis(router.urls) self.assertEqual(4, urls_created - len(apis))
def get_queryset(self): """ Allows a GET param, 'q', to be used against search_names. """ queryset = super(ModelViewSet, self).get_queryset() if self.request.GET.get('q', None): return queryset.filter( search_names__icontains=self.request.GET['q']) return queryset