I surely have not formulated the question correctly, I explain what the problem is.
I have in the model:
models.py
class Muro(models.Model):
tema = models.ForeignKey(Tematica,
on_delete=models.CASCADE,
verbose_name="Tematica",
)
...
class Historias(models.Model):
muro = models.ForeignKey(Muro,
on_delete=models.CASCADE,
verbose_name="Muro",
)
...
class Comentarios(models.Model):
historia = models.ForeignKey(Historias,
on_delete=models.CASCADE,
verbose_name="Historia",
)
...
In my application I have a wall by theme, each theme has its stories, then in each story I want to add comments.
I pass the pk through the url and filter the stories of each wall, the problem is when I want to filter the comments of each story, the pk no longer serves me, since I would need to filter by the pk of each story.
in my view I have:
views.py
def muro(request, pk):
cabeceraMuro = Muro.objects.get(pk=pk)
historias = Historias.objects.filter(muro__pk=pk)
comentarios = Comentarios.objects.filter(historia__muro__pk=pk)
context = {
'cabeceraMuro': cabeceraMuro,
'historias': historias,
'comentarios': comentarios,
}
return render(request, 'muro.html', context)
The header data of the wall all ok, in the stories of the wall all ok, but the comments are the same in all the stories, I can not get it to only show the comments that belong to each story only.
In my template:
muro.html
{% for historia in historias %}
<h1>Historia</h1>
...
<p>{{ historia.nombre }}</p>
<p>...</p>
...
<h3>Comentarios de la historia</h3>
{% for coment in comentarios %}
...
<p>{{ coment.comentario }}</p>
<p>...</p>
...
{% endfor %}
{% endfor %}
I'm stuck at this point. I have read in the django documentation about prefetch_related () I have tried with the examples, but I do not get it, on the contrary, I mix the comments of each theme.
I appreciate any help, thanks in advance.