查询Django中的ManyToMany字段

时间:2015-11-26 15:48:59

标签: python 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")

当我使用调试器时,我可以看到占用.skills,occupation.abilities ...是None。 如果我在django admin中检查一个职业对象,一切似乎都没问题,但我不能在模板中使用它们。

有人可以帮忙吗? 抱歉我的英文不好

1 个答案:

答案 0 :(得分:1)

您的模板中拼错了occupation

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

应该是

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

这是下次调试的提示。当for循环没有打印任何内容时,我会尝试包含我正在循环的查询集。

{{ ocuppation.skills.all }}

如果这不起作用,请尝试实例本身

{{ ocuppation }}

然后我会知道问题在于变量ocuppation,而不是多对多的字段。希望我能发现拼写错误。

相关问题