elliot727
elliot727

Reputation: 1

How to use 2 models in 1 view django?

So I have a model

class Question(models.Model):
question = models.CharField(max_length=255)
body = models.TextField()
author = models.ForeignKey(
    get_user_model(), 
    on_delete=models.CASCADE,
)

def __str__(self):
    return self.question

def check_answer(self, choice):
    return self.choice_set.filter(id=choice.id, is_answer=True).exists()

def get_answers(self):
    return self.choice_set.filter(is_answer=True)

def get_absolute_url(self):
    return reverse('article_detail', args=[str(self.id)])

and another model

class Choice(models.Model):
question = models.ForeignKey(Question, related_name='choices', on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
is_answer = models.BooleanField(default=False)
def __str__(self):
    return self.choice_text
def get_absolute_url(self):
    return reverse('article_list')

How can I display both of these in the same view OR is there a better way of doing this

Upvotes: 0

Views: 115

Answers (1)

Allen Shaw
Allen Shaw

Reputation: 1492

Solution 1:

You can directly use Question and Chioce in your template. Take DetailView as an example:

class QuestionView(DetailView):
    model = Question
    template_name = "question/question_list.html"

and in your template:

<h2>Questions</h2>
<div>
    <div>{{ object.body }} <br></div>
    <ul>
        {% for choice in object.choices.all %}
            <li>{{ choice.choice_text }} </li>
        {% endfor %}
    </ul>
</div>

Solution 2:

Override get_context_data(**kwargs):

class QuestionView(DetailView):
    model = Question
    template_name = "question/question_list.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        if self.object:
            context['choices'] = self.objects.chioces.all()
        return context

Upvotes: 2

Related Questions