我在模型中有两个类问答。两者都通过ForeignKey连接到用户。在模板中,我想打印用户中所有的looged答案。这很容易发生。但我的问题是我想得到与答案相对应的问题。获得问题的查询是什么?下面给出的模型,模板和视图 -
class Question(models.Model):
title = models.CharField(max_length=200, blank=True, null=True)
description = models.TextField()
pub_date = models.DateTimeField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
class Answer(models.Model):
answer_text = models.TextField()
questions = models.ForeignKey(Question, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
pub_date = models.DateTimeField()
def __str__(self):
return self.answer_text
的观点:
def answered_by_me(request, user_id):
user = User.objects.get(pk=user_id)
answers = user.answer_set.all()
questions = user.question_set.all()
context = {'answers': answers, 'questions': questions, 'user_id': user_id}
return render(request, template_name='ans/answered_by_me.html', context=context)
模板:
{% block body %}
{{ answers }}
{% if answers %}
<ul>
{% for answer in answers %}
<li> {{ answer }}</li>
{% endfor %}
</ul>
{% endif %}
{% endblock %}
答案 0 :(得分:0)
您不需要新的查询,除非您想将问题ID传递给您的视图。
不应循环答案,而应循环问题:
{% for question in questions %}
<li>{{ question }}</li>
{% for answer in question.answer_set.all %}
<li> {{ answer }}</li>
{% endfor %}
{% endfor %}
我认为这可行。