我有 3 个相互连接的模型。 GroupRequirementType --> GroupRequirement --> Requirement
.我试图在模板中显示所有要求。下一个代码仅显示 GroupRequirementsType 对象。好像我对_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 %}
看起来 Django 在将 CamelCase 模型名称转换为小写时不会自动添加下划线。 grouprequirement_set.all
有效。
我强烈建议在你的模型声明中使用 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 %}