Chartjs-Django chart.js – Query to get count of all distinct values for particular column

0👍

The solution requires modifying views.py in two parts, a new query and converting to list. The JS is fine.

def visuals(request):
    queryset = Arrest.objects.order_by('charge').values('charge').annotate(charge_count=Count('charge'))

    data = list(queryset.values_list('charge_count', flat=True))
    labels = list(queryset.values_list('charge', flat=True))

    return render(request, "data/visuals.html", {
    'labels': labels,
    'data': data,
    })

0👍

According to the documentation, I think you might have to check once again. But this might be the solution.

queryset = Arrest.objects.annotate(Count('charge'))
for arrest in queryset:
    data.append(arrest.charge__count)
    labels.append(arrest.name)

Here, I assume that labels refers to the name of each data and change your original code.

Leave a comment