2015-11-26 113 views
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中檢查職業對象,一切似乎都沒問題,但我不能在模板中使用它們。

誰能幫助? 抱歉我沒有說英語

+0

你確定'pk'必須等於'code'嗎? – pythad

+0

錯字:'{%for skill in ocuppation.skills.all%}''。它應該是:'{%爲佔領技能.skills.all%}' – Brandon

+0

我拼錯了模板中的職業。用{%爲技能在occupation.skills.all%}它運作良好。 –

回答

1

你有錯誤occupation在您的模板。

{% for skill in ocuppation.skills.all %} 

應該

{% for skill in occupation.skills.all %} 

下面是調試下一次提示。當for循環沒有打印任何東西時,我會嘗試包含我正在循環的查詢集。

{{ ocuppation.skills.all }} 

,如果沒有工作,嘗試實例本身

{{ ocuppation }} 

那我就知道問題出在可變ocuppation,不是多對多的領域。希望我會發現拼寫錯誤。