1

在我的 DRF API 中,我有这样的视图

class ActivityAPI(viewsets.ModelViewSet):
    authentication_classes = (SessionAuthentication, TokenAuthentication)
    serializer_class = ActivitySerializer
    queryset = Activity.objects.order_by('-id').all()
    filter_backends = (DjangoFilterBackend,)
    filter_class = ActivityFilter
    filter_fields = ('name', 'ack', 'developer', 'ack_date', 'ack_by', 'verb')    

    def get_count(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        if CASE_1:
            queryset = queryset.values('verb').annotate(count=Count('verb'))
        if CASE_2:
            queryset = Activity.objects.values('verb').annotate(count=Count('verb'))
        return Response(data=queryset)

CASE_2中,我得到了我所期望的,这相当于 SQL 查询 SELECTactivity_activity .verb , COUNT(activity_activity .verb ) AScount FROMactivity_activity GROUP BYactivity_activity .verbORDER BY NULL

但是当涉及到CASE_1时,注释功能将查询集分组activity.id,即SELECTactivity_activity .verb , COUNT(activity_activity .verb ) AScount FROMactivity_activity GROUP BYactivity_activity .id ORDER BYactivity_activity .idDESC

注意我需要 API 和聚合的基于 url 的过滤数据

4

1 回答 1

3

组是如此之小,因为您有.order_by('-id')原始查询集。您可以通过空 order_by 或仅按 group by 中使用的字段排序来修复它:

if CASE_1:
    queryset = queryset.values('verb').annotate(count=Count('verb')).order_by('verb')

阅读有关聚合 - 与默认排序或 order_by() 的交互

于 2017-11-07T09:20:10.487 回答