我正在使用来自 REST Framework 的 routers 来构建我的 URL。我尝试了上面的代码,但没有得到它的工作。问题之一是我无法让/count/ 进入路由器端点。
我检查了 DRF 文档 (3.8.2),发现有一个(新的?)@action 装饰器(我使用的是 3.7.7,但它没有)。所以,这是我的完整解决方案:
- 在
requirements.txt(或PipFile,如果您使用它)中将 DRF 升级到 3.8.2(或更高版本)。
- 向 ModelViewSet 添加一个新的操作
count 方法
- 更新
get_permissions 以包含新添加的操作count
这是我的views.py:
from rest_framework.decorators import action
from rest_framework.response import Response
class PostViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows recommend to be viewed or edited.
"""
model = Post
queryset = Post.objects.filter(is_active=True)
serializer_class = serializers.PostSerializer
filter_backends = (filters.SearchFilter, DjangoFilterBackend,)
search_fields = ('title', 'body',)
filter_fields = ('status', 'type')
def get_permissions(self):
if self.action in ('list', 'retrieve', 'create', 'count'):
return (AllowAny()),
if self.action in ('update', 'partial_update'):
return (IsAdminUser()),
return (IsAdminUser()),
@action(detail=False)
def count(self, request):
queryset = self.filter_queryset(self.get_queryset())
count = queryset.count()
content = {'count': count}
return Response(content)
- 查询发帖数:
/api/posts/count/?format=json
- 要查询已发布的计数:
/api/posts/count/?format=json&status=published
这里重要的一点是使用来自filter_queryset(...) 的查询集,而不是Post.objects.all()。
更新
由于count 很常见,我为此创建了一个mixin。
from rest_framework.decorators import action
from rest_framework.response import Response
class CountModelMixin(object):
"""
Count a queryset.
"""
@action(detail=False)
def count(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
content = {'count': queryset.count()}
return Response(content)
要使用它,只需将 CountModelMixin 添加到您的 ModelViewSet(也支持嵌套 ModelViewSet)。
class PostViewSet(viewsets.ModelViewSet, CountModelMixin):
如果您使用权限,还将'count' 添加到授予操作的列表中。