0

I'd like to build an API for a complex query.

Having read the documentation, I prefer using django-rest-framework, which will provide serialization and pagination automatically for a ValuesQuerySet, rather than doing my own serialization.

However, I only found docs for default model QuerySet and did not find any documentation for serializing ValuesQuerySet (when the model is not known). How can I do that?

I've seen this answer but the solution was not applicable in my case.

Here is the code, NOT using django-rest-framework:

@login_required
def category_tallies(request):
    my_friends = FacebookUser.objects.filter(user_id=request.user.id)
    cat_tallies = FacebookLike.objects.filter(id__in=my_friends).values('category').annotate(Count('category')).order_by('-category__count')
    return HttpResponse(
        json.dumps(cat_tallies),
        mimetype='application/json')

1 Answer 1

1

Try this:

from django.core import serializers

cat_tallies = FacebookLike.objects.filter(id__in=my_friends).annotate(count=Count('category')).order_by('-count')
json_dump = serializers.serialize('json', cat_tallies, fields=('category','count'))
Sign up to request clarification or add additional context in comments.

2 Comments

Can serializers.serialize do pagination?
All paginator needs is an iterable. So, yes you can

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.