Reputation: 105
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
Reputation: 477607
You can access the related Chart
s 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 Chart
s 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 Category
s, and N queries to fetch each time the related chart_set
of a category.
Upvotes: 1