Dimitur Dimitrov
Dimitur Dimitrov

Reputation: 51

Access object value by other object value in template in Django?

This {{ category.id }} returns me 1

This {{ categories_counts.1 }} returns me data

But {{ categories_counts.category.id }} doesn't work?

Is it possible to access value by other object value?

views.py:

categories = Category.objects.all()
categories_counts = {}
for category in categories:
    count = Venue.objects.filter(category_id=category.id).count()
    categories_counts[category.id] = count

So categories containst:

<QuerySet [<Category: restaurants>, <Category: sportfitness>, <Category: carservices>, <Category: beautysalons>]>

categories_counts contains:

{1: 1, 2: 0, 3: 0}

category Model:

class Category(models.Model):
    name = models.CharField(max_length=20)
    bg_name = models.CharField(max_length=20, default=None)
    category_bg_name = models.CharField(max_length=100, default=None)

Upvotes: 0

Views: 544

Answers (1)

Alasdair
Alasdair

Reputation: 308879

In general, you can't access categories_counts[category.id] in the Django template unless you create a custom template tag, as @sayse says in the comments.

In your specific case, you can annotate the queryset with the venue counts.

from django.db.models import Count
categories = Category.objects.annotate(num_venues=Count('venue'))

Then in your template you can do something like:

{% for category in categories %}
{{ category.name }} has {{ category.num_venues }} venue(s)
{% endfor %}

Upvotes: 1

Related Questions