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

后端 未结 4 1725
不知归路
不知归路 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条回答
  •  时光说笑
    2020-12-20 23:59

    As shown in this post you can use SerializerMethodField in your Serializer:

    class BooksSerializer(serializers.ModelSerializer):
    
      num_books = serializers.SerializerMethodField()
    
      def get_num_books(self, obj):
        try:
            return obj.num_books
        except:
            return None
    

    It will serialize the annotated value (readonly)

提交回复
热议问题