我在Django中有以下自定义模型管理器,用于统计相关注释的数量并将它们添加到对象查询集中:
class PublicationManager(models.Manager):
def with_counts(self):
return self.annotate(
count_comments=Coalesce(models.Count('comment'), 0)
)
将此管理器添加到模型中不会自动添加DRF中的额外字段。在我的API视图中,我找到了一种通过重写get函数来检索count_comments
字段的方法,例如:
class PublicationDetails(generics.RetrieveUpdateAPIView):
queryset = Publication.objects.with_counts()
...
def get(self, request, pk):
queryset = self.get_queryset()
serializer = self.serializer_class(queryset.get(id=pk))
data = {**serializer.data}
data['count_comments'] = queryset.get(id=pk).count_comments
return Response(data)
这适用于单个实例,但是当我尝试将其应用于使用pagination_class
的分页列表视图时,重写get方法似乎删除了分页功能(即我获得结果列表而不是通常的带有previous, next等的页面对象)。这让我相信我做错了什么:我应该将自定义管理器的额外字段添加到序列化器中吗?鉴于我正在使用模型序列化器,我不确定如何继续。我应该使用基本的序列化器吗?
更新
事实证明,我完全错误地使用了模型管理器。当我真正想要的是行级功能来计算与单个实例相关的注释数量时,我不理解表级功能的想法。我现在使用自定义get_paginated_response
方法与Comment.objects.filter(publication=publication).count()
。
get_paginated_response
方法解决了这个问题。
class PaginationPublication(pagination.PageNumberPagination):
def get_paginated_response(self, data):
for item in data:
publication = Publication.objects.with_counts().get(id=item['id'])
item['count_comments'] = publication.count_comments
return super().get_paginated_response(data)
不确定这是最有效的解决方案,但它有效!
标题>