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

与世无争的帅哥 提交于 2019-12-29 09:09:15

问题


How can you include annotated results in a serialized QuerySet?

data = serializer.serialize(Books.objects.filter(publisher__id=id).annotate(num_books=Count('related_books')), use_natural_keys=True)

However the key/value pare {'num_books': number} is not include into the json result.

I've been searching for similar questions on the internet, but i didn't found a solution that worked for me.

Here is a similar case: http://python.6.x6.nabble.com/How-can-you-include-annotated-results-in-a-serialized-QuerySet-td67238.html

Thanks!


回答1:


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)



回答2:


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}]



回答3:


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.



来源:https://stackoverflow.com/questions/25401103/django-how-can-you-include-annotated-results-in-a-serialized-queryset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!