How can I forloop this count() in my template code?

16 views
Skip to first unread message

Pepsodent Cola

unread,
Nov 20, 2013, 6:18:23 AM11/20/13
to django...@googlegroups.com
How can I forloop this count() in my template code?

* I have attached my project files that you might run and see for yourselves.
* I have attached a screenshot of the table I'm working on.
* User/Pass = joe/joe


def index(request):
    publications = Publication.objects.all()
    articles = Article.objects.all()

    sum_publications = Publication.objects.filter(article__pk=1).count()

    context = {'publications':publications, 'articles':articles, 'sum_publications':sum_publications}
    return render(request, 'magazine/index.html', context)



<article>
    <h1>How many Publications was each Article in?</h1>

{% if articles %}
    <table border="1">
    <tr>
        <th>Article id</th>
        <th>Article</th>
        <th>Publication</th>
    </tr>
    {% for row in articles %}
    <tr>
        <td>{{ row.id }}</td>
        <td>{{ row.headline }}</td>
        <td>total</td>
    </tr>
    {% endfor %}
    </table>
{% else %}
    <p>No Articles are available.</p>
{% endif %}


<!-- TypeError: 'int' object is not iterable -->
{% if 666sum_publications %}
    <ul>
    {% for row in sum_publications %}
        <li>{{ row }}</li>
    {% endfor %}
    </ul>
{% else %}
    <p>No sums are available.</p>
{% endif %}

    <hr>
</article>


ManyToMany_public_01.tar.gz
Publication_Article_01.png

Tom Evans

unread,
Nov 20, 2013, 6:32:51 AM11/20/13
to django...@googlegroups.com
On Wed, Nov 20, 2013 at 11:18 AM, Pepsodent Cola
<pepsod...@gmail.com> wrote:
> How can I forloop this count() in my template code?
>
> * I have attached my project files that you might run and see for
> yourselves.
> * I have attached a screenshot of the table I'm working on.
> * User/Pass = joe/joe
>
>
> def index(request):
> publications = Publication.objects.all()
> articles = Article.objects.all()
>
> sum_publications = Publication.objects.filter(article__pk=1).count()
>
> context = {'publications':publications, 'articles':articles,
> 'sum_publications':sum_publications}
> return render(request, 'magazine/index.html', context)

Are you trying to annotate each row in the 'articles' queryset with
the count of the number of publications associated with that article?

from django.db.models import Count
articles = Article.objects.all().annotate(num_publications=Count('publication'))

{% for article in articles %}
{{ article.id }}
{{ article.num_publications }}
{% endfor %}

Cheers

Tom

Pepsodent Cola

unread,
Nov 20, 2013, 10:10:41 AM11/20/13
to django...@googlegroups.com
Thanks Tom it worked! :)
Reply all
Reply to author
Forward
0 new messages