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
)
- [Django]-Django serializer ManyToMany retrun array of names instead of an array of IDs
- [Django]-Django – decorators restrict "staff"
- [Django]-Ordering in a Python module
- [Django]-I added a SECRET_KEY config variable to my Django app on Heroku but now it won't work locally
- [Django]-Why Django's ModelAdmin uses lists over tuples and vice-versa
Source:stackexchange.com