0
I`ve了這些定義的模型在Django查詢多對多領域
class Occupation(models.Model):
title = models.CharField(max_length=150)
code = models.CharField(max_length=10)
what_they_do = models.TextField(blank=True, default="")
skills = models.ManyToManyField(Skill)
knowledge = models.ManyToManyField(Knowledge)
abilities = models.ManyToManyField(Ability)
technologies = models.ManyToManyField(Technology)
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.title
,知識,技術,技能,能力是相似的。我用過這個結構。
class Skill(models.Model):
title = models.CharField(max_length=64)
element_id = models.CharField(max_length=10)
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.title
在我的模板,我目前有:
<ul>
{% for skill in ocuppation.skills.all %}
<li>{{skill.title}}</li>
{% endfor %}
</ul>
但{{skill.title}}是空白。
在我的views.py,我已經定義了這一點:
def detail(request, pk):
possible_occupation = Occupation.objects.filter(code=pk)
occupation = possible_occupation[0] if len(possible_occupation) == 1 else None
if occupation is not None:
context = {
'occupation': occupation
}
return render(request, 'careers/detail.html', context)
else:
return HttpResponseNotFound("No hay datos")
當我使用調試器,我可以看到occupation.skills,occupation.abilities ......沒有。 如果我在django admin中檢查職業對象,一切似乎都沒問題,但我不能在模板中使用它們。
誰能幫助? 抱歉我沒有說英語
你確定'pk'必須等於'code'嗎? – pythad
錯字:'{%for skill in ocuppation.skills.all%}''。它應該是:'{%爲佔領技能.skills.all%}' – Brandon
我拼錯了模板中的職業。用{%爲技能在occupation.skills.all%}它運作良好。 –