django注释奇怪的行为(按model.id分组)
Posted
技术标签:
【中文标题】django注释奇怪的行为(按model.id分组)【英文标题】:django annotate weird behavavior (group by model.id) 【发布时间】:2018-04-19 07:55:32 【问题描述】:在我的 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查询SELECT
activity_activity.
verb, COUNT(
activity_activity.
verb) AS
countFROM
activity_activity@987654328 @activity_activity.
verbORDER BY NULL
但是当涉及到 CASE_1 时,注释功能将查询集按 activity.id
分组,即 SELECT
activity_activity.
verb , COUNT(
activity_activity.
verb) AS
countFROM
activity_activityGROUP BY
activity_activity.
idORDER BY
activity_activity.
idDESC
注意 API 和聚合都需要基于 url 的过滤数据
【问题讨论】:
【参考方案1】:组非常小,因为您在原始查询集上有.order_by('-id')
。您可以通过空 order_by 或仅按 group by 中使用的字段排序来修复它:
if CASE_1:
queryset = queryset.values('verb').annotate(count=Count('verb')).order_by('verb')
了解Aggregation - Interaction with default ordering or order_by()。
【讨论】:
以上是关于django注释奇怪的行为(按model.id分组)的主要内容,如果未能解决你的问题,请参考以下文章