为什么_set.all不能在tempale工作?

时间:2017-05-23 17:16:59

标签: python html django python-3.x django-1.10

我有3个相互连接的模型。 GroupRequirementType --> GroupRequirement --> Requirement。我想在模板中显示所有要求。下一个代码只显示GroupRequirementType对象。好像我有_set.all的问题。怎么了?

models.py:

class GroupRequirementType(models.Model):
    name = models.CharField(_('Name'), max_length=250)

class GroupRequirement(models.Model):
    group_requirement_type = models.ForeignKey(GroupRequirementType, on_delete=models.CASCADE)
    name = models.CharField(_('Name'), max_length=250)

class Requirement(models.Model):
    group_requirement = models.ForeignKey(GroupRequirement, on_delete=models.CASCADE)
    name = models.CharField(_('Name'), max_length=250)

模板:

{% for group_requirement_type in group_requirement_types %}
   {{ group_requirement_type }}

   {% for group_requirement in group_requirement_type.group_requirement_set.all %} <!--DONT WORK. WHY?-->
      {{ group_requirement }}

      {% for requirement in group_requirement.requirement_set.all %}
         {{ requirement }}
      {% endfor %}

   {% endfor %}

{% endfor %}

2 个答案:

答案 0 :(得分:0)

看起来Django在将CamelCase模型名称转换为小写时不会自动添加下划线。 df[,lapply(.SD,table),.SDcols = sapply(df,is.factor)]有效。

答案 1 :(得分:0)

我强烈建议在模型声明中使用Django ForeignKey related_name属性,这会使向后关系操作变得更加容易:https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.ForeignKey.related_name

在你的情况下,它会变成类似

的东西

<强> models.py:

class GroupRequirementType(models.Model):
    name = models.CharField(_('Name'), max_length=250)

class GroupRequirement(models.Model):
    group_requirement_type = models.ForeignKey(GroupRequirementType, related_name='group_requirements', on_delete=models.CASCADE)
    name = models.CharField(_('Name'), max_length=250)

class Requirement(models.Model):
    group_requirement = models.ForeignKey(GroupRequirement, related_name='requirements', on_delete=models.CASCADE)
    name = models.CharField(_('Name'), max_length=250)

<强>模板:

{% for group_requirement_type in group_requirement_types %}
    {{ group_requirement_type }}

    {% for group_requirement in group_requirement_type.group_requirements.all %} <!--DONT WORK. WHY?-->
        {{ group_requirement }}

        {% for requirement in group_requirement.requirements.all %}
            {{ requirement }}
        {% endfor %}

    {% endfor %}

{% endfor %}