Seyed Amir Mousavian
Seyed Amir Mousavian

Reputation: 105

using Foreign Key value in if condition in Django Template

I have a model that have a Foreign Key in it. like this:

class Chart(models.Model):
     titleFA     = models.CharField(max_length=200)
     titleEN     = models.CharField(max_length=200)
     category = models.ForeignKey(Category, on_delete=models.PROTECT, blank=True)

category related to this model:

class Category(models.Model):
     nameEN = models.CharField(max_length=200, default="")

and this is the view file:

def drawcharthome(request):
   allcharts = Chart.objects.all()
   allcats = Category.objects.all()
   return render(request, 'charts/drawcharthome.html',{'allcharts': allcharts,'allcats':allcats})

I need to check the equality of two parameter in my template:

{% for  cat in allcats %}
   {% for  chart in allcharts %}
      {% if chart.category == cat.nameEN %}
        <li>
          <a href="{{ chart.api_url }}"> {{ chart.titleFA }}</a>
        </li>
      {% endif %}
   {% endfor %}
{% endfor %}

but my inner if do not work!

Upvotes: 1

Views: 907

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477607

You can access the related Charts of a Category object with my_category.chart_set, so you implement this with:

def drawcharthome(request):
    allcats = Category.objects.prefetch_related('chart_set')
    return render(request, 'charts/drawcharthome.html',{'allcats':allcats})

and render this in the template with:

{% for cat in allcats %}
    {% for chart in cat.chart_set.all %}
         <li>
             <a href="{{ chart.api_url }}"> {{ chart.titleFA }}</a>
          </li>
    {% endfor %}
{% endfor %}

The .prefetch_related(…) [Django-doc] is not necessary, but it will load all the related Charts with a single query and do the joining in the Django/Python layer, which will result in two queries instead of N+1 where you make one query to fetch the Categorys, and N queries to fetch each time the related chart_set of a category.

Upvotes: 1

Related Questions