0

I am having issues with accessing data through a django one to many relationship. After 3 painstaking days I figured out a way to display the data from the relationship by overriding the get_context_data method. I was wondering if that was the proper way to do it. This works but I could imagine that there is a better way to do this that I missed in the documentation.

Here is the code for that:

class QuestionDetailView(DetailView):
    model = Question

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['answers'] = Answer.objects.filter(firm=context['object'])
        return context

Here is the code for the models:

 class Question(models.Model):
    text = models.CharField(max_length=120, unique=True)

class Answer(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)

Here is the code in my template:

    {% extends "base.html" %}
    {% block body %}

   <div class="">
      <h3>{{ object.text }}</h3>

      <p>Answers:</p>
      <ul>
        {% for answer in answers %}
          <li> {{ answer }}</li>
        {%empty%}
          <li>No answers</li>
        {% endfor %}
      </ul>
    </div>
    {% endblock %}

1 Answers1

3

Add a related_name to your question field.

class Answer(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name="answers")

Or, just use the default that Django gives: answer_set

Then in your template, you can do:

{% for answer in object.answers.all %} 
  <li> {{ answer }}</li>
{% empty %}
  <li>No answers</li>
{% endfor %}

No need to override get_context_data unless you want to do something more specific with the queryset.

ChidG
  • 3,053
  • 1
  • 21
  • 26
  • You don't need to explicitly set a related name, If you don't, a foreign key called `foo` to a model `Bar` will create a backward relation with the name `foo_set` in `Bar`. (You can set `related_name='+'` to prevent this). – nigel222 Jan 28 '20 at 11:16
  • Yes, that is why I said just use the default that Django gives: `answer_set` – ChidG Jan 29 '20 at 02:33
  • When I tried accessing the answer_set I would always get an empty set. But I will try it with the related name. – Damali B Jan 30 '20 at 04:20
  • There shouldn't be any difference. If you got an empty set, that means you haven't added any answers to the question object. – ChidG Jan 30 '20 at 05:03