我有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 %}
答案 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 %}