Search code examples
pythondjangodjango-viewsdjango-template-filters

How to count occurences in list with template filters in django and pass them to the template


I have a django app in which I am counting the clicked urls. I am saving the clicked urls in a list in my view. Now I want to iterate through the list and count each occurence (of the urls). Then I want to show each url with the counted number in the template. What I am doing so far looks like this:

My view:

class AnalyticsIndexView(StaffRequiredMixin, ListView):
  template_name = 'analytics_list.html'
  model = UrlTime

  def get_context_data(self, **kwargs):
    context = super(AnalyticsIndexView, self).get_context_data(**kwargs)
    context['url_views_list'] = UrlTime.objects.all()
    context['total_views'] = UrlTime.objects.all().count

    context['home_view'] = UrlTime.objects.filter(associated_url='/').count()
    context['job_list'] = UrlTime.objects.filter(associated_url='/jobs/').count()
    context['job_detail'] = UrlTime.objects.filter(associated_url='/jobs/{How to pass id??}').count()
    context['job_'] = UrlTime.objects.filter(associated_url='/jobs/{???id?????}').count()

    return context

Now that works. But I don't want to hardcode the links obviously, also because I don't know which urls will be in it. (that handles my custom middleware). I would like to capture each url in the list, count it, and show link and linkcount in the template. I already tried with Collections but it didn't work as I wanted it. Also with the harcoding I don't know how to do that with links that have a dynamic id....

Anyone has any suggestions? Help is very much appreciated. Thanks!


Solution

  • You need to do a GroupBy and Count aggregation. Try overriding get_query_set method with the following query:

    def get_queryset():
        return UrlTime.objects.values('associated_url').annotate(
            url_count=Count('associated_url')
        )