[Django]-Object of type QuerySet is not JSON serializable

3👍

If you know what fields you want to pass to chart.js, you can do a specific values() query to get a dictionary, which you can easily serialize with json.dumps, more or less like this:

user_lists = (List.objects
    .filter(user=user)
    .select_related('user')
    .prefetch_related('data_items')
    .values('user__username', 'data_items__data')  # all fields you need
)

list_data_json = json.dumps(list(user_lists))

1👍

despite what one could expect, DjangoJSONEncoder doesn’t handle querysets nor models instances (see here for the types DjangoJSONEncoder deals with) – this part is actually handled by the serializer itself, but a serializer expects a Queryset and not a dict of querysets.

IOW, you will have to write your own encoder (based on DjangoJSONEncoder) to handle querysets and models (hint: someobj.__dict__ returns the object’s attributes as a dict, which you can filter out to remove irrelevant django stuff like _state)

Leave a comment