I did some research and found that serializer.serialize
can only serialize queryset, and annotation just adds an attribute with each object of the queryset, so when you try to serialize a query, annotated fields aren't shown. This is my way of implementation:
from django.core.serializers.json import DjangoJSONEncoder
books = Books.objects.filter(publisher__id=id).annotate(num_books=Count('related_books')).values()
json_data = json.dumps(list(books), cls=DjangoJSONEncoder)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…