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

后端 未结 4 1750
不知归路
不知归路 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-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.

提交回复
热议问题