如何在django-rest-framework查询响应中添加注释数据? [英] how to add annotate data in django-rest-framework queryset responses?

查看:362
本文介绍了如何在django-rest-framework查询响应中添加注释数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为QuerySet中的每个项目生成聚合:

I am generating aggregates for each item in a QuerySet:

def get_queryset(self):
    from django.db.models import Count
    queryset = Book.objects.annotate(Count('authors'))
    return queryset

但我没有得到JSON响应中的计数。

But I am not getting the count in the JSON response.

提前谢谢。

推荐答案

从get_queryset返回的查询器提供了将通过序列化程序的事物的列表,该列表控制对象将如何被表示。尝试在您的书籍序列化程序中添加一个附加字段,如:

The queryset returned from get_queryset provides the list of things that will go through the serializer, which controls how the objects will be represented. Try adding an additional field in your Book serializer, like:

author_count = serializers.IntegerField(
    source='author_set.count', 
    read_only=True
)

这篇关于如何在django-rest-framework查询响应中添加注释数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆