0

im building a survey app or something similar, each question has three or more answer, i cant get it works that in the template, i mean, nest the question with the corresponding answers, this are my models:

class Trivia(models.Model):
    nombre = models.CharField(max_length=100)
    slug = models.SlugField(unique=True)
    categoria = models.ForeignKey(Categorias)
    contador = models.IntegerField()

    def __str__(self):
      return self.nombre

class Meta():
    verbose_name_plural = "Trivias" 

class Preguntas(models.Model):
    trivia = models.ForeignKey(Trivia)
    pregunta = models.CharField(max_length=100)

    def __str__(self):
        return self.pregunta

    class Meta():
        verbose_name_plural = "Preguntas"

class Respuestas(models.Model):
    Pregunta = models.ForeignKey(Preguntas)
    respuesta = models.CharField(max_length=100)

    def __str__(self):
        return self.respuesta

    class Meta():
        verbose_name_plural = "Respuestas"

and my views:

class TriviaView(ListView):
    model = Preguntas
    paginate_by = 1
    template_name = 'trivias.html'

And this my template:

 <p>{% for pregunta in object_list %} {{pregunta.pregunta}} {% endfor %}</p>

How can i nest the question with their corresponding answers?

Sorry for the spanish attributes named, my client asked like that

1 Answer 1

4

List of Respuestas is available as the pregunta.respuestas_set backward relation queryset:

{% for pregunta in object_list %}
    {{ pregunta.pregunta }}
    <ul>
    {% for respuesta in pregunta.respuestas_set.all %}
        <li>{{ respuesta.respuesta }}</li>
    {% endfor %}
    </ul>
{% endfor %}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.