2015-10-13 82 views
0

我有models.py如下:Django的:FOREIGNKEY查询

class Article(models.Model): 
    board = models.ForeignKey(Board) 
    subject = models.CharField("과목명", max_length=10) 
    ... 

class Question(models.Model): 
    user = models.ForeignKey(User) 
    article = models.ForeignKey(Article) 
    professor = models.CharField("출제교수", max_length=4) 
    ... 

Views.py:

def get_q_table(request): 
    context = { 
     "q_list" : Question.objects.all().order_by("number") 
    } 
    return render(request, "q_table.html", context) 

我想某种方式传递有关实例q_table.html,但无法找到一种方法来做到这一点。我应该像下面的(当然,这不完全正确,我一直在寻找外键查询的单证,但我不出路“:如果我想出路

def get_q_table(request): 
context = { 
    "q_list" : Question.objects.all().order_by("number") 
    "article" : Question.objects.all().related_board 
} 
return render(request, "q_table.html", context) 

,然后下面的模板应该工作:

<div class="container"> 
    <div class="page-header"><h3>{{article.subject}} : {{article.year}}년 {{article.semester}}학기 {{article.quarter}}Q</h3></div> 
    <div> 
     <ul class="list-group" id="visitorbook"> 
     {% for question in questions %} 
      <li class="list-group-item">{{question.number}} : {{ question.question }} - {{ question.answer }} 
      </li> 
     {% endfor %} 
     </ul> 
    </div> 
</div> 

回答

1

在模板中,认为应该是:

{% for question in q_list %} 
1

你取aricle对象;

articles = Article.objects.all()

{% for article in articles %} 
<div class="container"> 
    <div class="page-header"><h3>{{article.subject}} : {{article.year}}년 {{article.semester}}학기 {{article.quarter}}Q</h3></div> 
    <div> 
    <ul class="list-group" id="visitorbook"> 
    {% for question in article.question_set.all %} 
     <li class="list-group-item">{{question.number}} : {{question.question }} - {{ question.answer }} 
     </li> 
     {% endfor %} 
     </ul> 
    </div> 
</div> 
{% endfor %} 
如果你想获取只有一个文章,然后

;

articles = Article.objects.get(id=id)` 


<div class="container"> 
    <div class="page-header"><h3>{{article.subject}} : {{article.year}}년 {{article.semester}}학기 {{article.quarter}}Q</h3></div> 
    <div> 
    <ul class="list-group" id="visitorbook"> 
    {% for question in article.question_set.all %} 
     <li class="list-group-item">{{question.number}} : {{question.question }} - {{ question.answer }} 
     </li> 
     {% endfor %} 
     </ul> 
    </div> 
</div> 
1

提供的,该物品是为所有问题一样,你可以尝试这样的事情:

{% with article=questions.0.article %} 

<div class="container"> 
    <div class="page-header"><h3>{{article.subject}} : {{article.year}}년 {{article.semester}}학기 {{article.quarter}}Q</h3></div> 
    <!-- other stuff --> 
</div> 

{% endwith %} 

尽管您应该在问题列表为空时以最适合您的方式处理案例。另外请注意,您不需要将“文章”添加到上下文中。