ilyas Jumadurdyew
ilyas Jumadurdyew

Reputation: 930

Count objects assigned to the category in a django cycle

I've a cycle in my template, which get's all the categories like this:

<div class="panel">
    <h4 class="title1">Категории</h4>
        <ul class="clear-list">
        {% for categ in categs %}
            <li>
                <a href="/advert/adverts.aspx&cat{{ categ.id }}">{{ categ.name }}</a>
            </li>
        {% endfor %}
        </ul>
</div>

And my views.py looks like:

def adverts(request):
    args = {}
    args.update(csrf(request))
    args['adverts'] =  Advert.objects.all().order_by('-advert_date', '-id')
    args['sections'] = AdvertSection.objects.all().order_by('-name')
    args['categs'] = AdvertCategory.objects.all().order_by('-name')
    args['username'] = auth.get_user(request).username
    return render_to_response('adverts.html', args)

Now comes question....

How to show total count of objects attached to the category?

Output:

Category1
Category2
Category3

Expected Output:

Category1(115)
Category2(546)
Category3(832)

Please help me...

Upvotes: 1

Views: 952

Answers (1)

Leistungsabfall
Leistungsabfall

Reputation: 6488

Assuming the objects attached to your categories are called Adverts:

{% for categ in categs %}

    {{ categ.name }} ({{ categ.advert_set.count }})

{% endfor %}

If you changed the attribute related_name of your Adverts in the Category ModelClass in your models.py file you'll have to adjust advert_set to the corresponding related_name.

For more information about how to access related objects take a look at the docs.

Upvotes: 2

Related Questions