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

后端 未结 4 1726
不知归路
不知归路 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: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)
    
    0 讨论(0)
  • 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)

    0 讨论(0)
  • 2020-12-21 00:09

    To get count from specific columns, you must declare them via values method

    >>>> Books.objects.filter(publisher__id=id).values('<group by field>').annotate(num_books=Count('related_books'))
    [{'num_books': 1, '<group by field>': X}]
    
    0 讨论(0)
  • 2020-12-21 00:11

    Based on the link, this has been solved by pull request (https://github.com/django/django/pull/1176) some months ago.

    You need to add num_books as a property:

    class Publisher():
        ....
    
        @property
        def num_books(self):
            return some_way_to_count('related_books')
    

    and then call it like so:

    data = serializer.serialize(Books.objects.filter(publisher__id=id)), use_natural_keys=True, extra=['num_books'])
    

    I'm not too sure about the exact syntax, since I don't work much with serializers.

    0 讨论(0)
提交回复
热议问题