Chartjs-How to write a query to get the number of times a choice is selected by users

1👍

You can’t do that at the database level if you’re using a MultiSelectField because the underlying value is just stored as CharField in the database. So values('illness') will only group by equal strings, i.e. combinations of illnesses.

So either do this in python, after you’ve fetched all the instances: Initialize a dict of counters, loop through the instances in your queryset and update the counters one by one. Note: This won’t scale when the number of MedicalHistory rows in your table becomes large.

Or model your Illness as a separate model (don’t use MultiSelectField), use a ManyToMany relationship and count those. Then you can do this in a queryset. This will scale with a very large number of rows.

Leave a comment