0

I would like to loop over some objects placed into a list and get statistics on each one. I'm using Django 1.11.16

User can select one or multiple publication(s) and I display some statistics over each publication in the list.

I have a view part which looks like this :

def get_context_data(self, **kwargs):

    publication_list = self.request.GET.getlist('publication_list')

    publication_selected = Publication.objects.filter(id__in=publication_list)

    download_all_period = Download.objects.values('usage', 'doc__publication__pub_id') \
                    .filter(
                        doc__publication__id__in=publication_list) \
                    .filter(
                        Q(creation_date__gte=start_date) & Q(creation_date__lte=end_date))\
                    .aggregate(
                        nusage=Sum('usage'))

    request_all_period = Download.objects.values('doc__publication__pub_id')\
                    .filter(
                        doc__publication__id__in=publication_list)\
                    .filter(
                        Q(creation_date__gte=start_date) & Q(creation_date__lte=end_date))

    all_period_list = zip(publication_selected, download_all_period, request_all_period)

    context_data['publication_list'] = publication_list
    context_data['publication_selected'] = publication_selected
    context_data['download_all_period'] = download_all_period
    context_data['request_all_period'] = request_all_period
    context_data['all_period_list'] = all_period_list

return context_data

Then I have a template, with a table. So I would like to loop over each element in my list in order to create one row per element :

{% for publication_selected, download_all_period, request_all_period in all_period_list %}
  {% if download_all_period.nusage %}
    <tr>
      <td>{{ start_date|date:"Y/m/d" }} to {{ end_date|date:"Y/m/d" }}</td>
      <td>{{ publication_selected }}</td>
      <td><span class="badge alert-danger">{{ download_all_period.nusage }}</span> / <span
        class="badge alert-info">{{ request_all_period.count }}</span></td>
    </tr>

  {% else %}
    <tr>
      <td>{{ start_date|date:"d/m/Y" }} to {{ end_date|date:"d/m/Y" }}</td>
      <td>{{ publication_selected }}</td>
      <td>{% trans 'No downloads/No requests' %}</td>
    </tr>
  {% endif %}
{% endfor %}

It displays only the last object in my list and I am always inside the {% else %} part while I can print statistics for this specific object.

1 Answer 1

1

You must use ANNOTATE not AGGREGATE in download_all_period query,

https://stackoverflow.com/a/45983784/6348368

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.