Reputation: 33
I have these list objects that are callable by name. They have number values that users can input. how would I turn each of those lists to form that chart js can render? I tried with this: Django Queryset to dict for use in json but could not get it working. Getting "Object of type QuerySet is not JSON serializable". Chart js would need to have own line for each of those list and show the values in those lines. This is how far I got with the link in views:
First I get all of users lists:
user_lists = List.objects.filter(user=user)
Then I get number values for each list
list_data = {}
for list in user_lists:
list_data[list.name] = DataItem.objects.filter(list=list)
Here is where I get stuck when I should convert these lists to something that chart.js can understand..
list_data_json = json.dumps(list_data, cls=DjangoJSONEncoder)
btw am I in the right tracks to put this conversion to views, right? or does it belong somewhere else?
Dont know if these are needed but here are models for these lists and the data items in them:
class List(models.Model):
name = models.CharField(max_length=100, default="")
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='lists')
def __str__(self):
return self.name
class Meta:
unique_together = ['name', 'user']
class DataItem(models.Model):
data = models.IntegerField(default=0)
list = models.ForeignKey(List, on_delete=models.CASCADE, related_name='data_items')
EDIT output query set looks like this (this is what json.dumps is trying to read i quess):
<QuerySet [{'name': 'squat', 'data_items__data': 1}, {'name': 'deadlift', 'data_items__data': 55}, {'name': 'Chest', 'data_items__data': None}, {'name': 'asd', 'data_items__data': 444}, {'name': 'asd', 'data_items__data': 32342}, {'name': 'asd', 'data_items__data': 42342}]>
And for me that looks good, there is a list of lists and list has a name "squats" and then values. But getting this error again "'QuerySet' object is not callable"
Upvotes: 2
Views: 7873
Reputation: 5740
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))
Upvotes: 3
Reputation: 77932
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
)
Upvotes: 1