![](/img/trans.png)
[英]How Can I query Django Models with Foreign and OneToOneFields for Field Values
[英]How do i work with 3 django models linked by a foreign field?
我已經能夠在選舉中顯示所有辦公室,但無法在同一頁面上顯示辦公室中的所有候選人
模型.py
class Election(models.Model):
name = models.CharField(max_length = 30)
slug = models.SlugField(max_length = 250, null = False, unique = True)
class Office(models.Model):
election = models.ForeignKey(Election, on_delete=models.CASCADE, default=None)
name = models.CharField(max_length = 30)
class Candidate(models.Model):
office = models.ForeignKey(Office, on_delete=models.CASCADE, default=None)
name = models.CharField(max_length = 30)
視圖.py
def poll(request, id):
context = {
'election' : Election.objects.get(pk=id),
'off' : Office.objects.all()
}
return render(request, 'poll.html', context)
輪詢.html
{% for office in election.office_set.all %}
<div class="text-center">
<h3>{{ office.name }}</h3>
{% for candidate in off.candidate_set.all %}
<h5><a href="">{{ candidate.name }}</a></h5>
{% endfor %}
</div>
{% endfor %}
在您的第一行 poll.html 中,您從查詢集“election.office_set.all”中調用“office”
因此,當您調用該 QS 的子查詢時,您必須引用原始名稱,即:office,而不是 off。
您的最終代碼應如下所示:
輪詢.html
{% for office in election.office_set.all %}
<div class="text-center">
<h3>{{ office.name }}</h3>
{% for candidate in office.candidate_set.all %}
<h5><a href="">{{ candidate.name }}</a></h5>
{% endfor %}
</div>
{% endfor %}
你也不需要這條線
'off' : Office.objects.all()
在您的 Views.py 中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.