Django - How can you include annotated results in a serialized QuerySet?

后端 未结 4 1753
不知归路
不知归路 2020-12-20 23:09

How can you include annotated results in a serialized QuerySet?

data = serializer.serialize(Books.objects.filter(publisher__id=id).annotate(num_books=Count(         


        
4条回答
  •  猫巷女王i
    2020-12-20 23:58

    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)
    

提交回复
热议问题