django:related_name的自相关ForeignKey字段不起作用|在模板中获得自引用的相反方向



Hej!:(

我有一个创建单个机构(Institution(的模型,可以通过parent_institution(self(将其连接到父机构。

因此,我有一个机构A,它是b、c、d的父机构(所有这些机构都是单独的机构,有自己的详细视图。

<p><b>Parent institution: </b>
{% if institution.parent_institution %}
<a href="{% url 'stakeholders:institution_detail' institution.parent_institution.id %}">
{{institution.parent_institution}}
</a>
{% endif %}
</p>

通过此链接,我可以访问A的详细视图,在那里我想要一个关于儿童机构的部分。应列出b、c、d

我为parent_institution添加了一个相关名称

class Institution(models.Model):
name = models.CharField(
verbose_name=_("Name of the institution"),
max_length=200,
)
parent_institution = models.ForeignKey(
"self",
verbose_name=_("Parent institution"),
on_delete=models.SET_NULL,
blank=True,
null=True,
help_text=_("if applicable"),
related_name="child",
)

通常我可以通过这个related_name沿着相反的方向跟随ForeignKey。

<p><b>Child institution: </b>
{{institution.child.name}}
</p>

但在这种情况下,这不起作用,给了我"无"。为此我尝试了:

{% if institution.id == institution.all.parent_institution.id %}
{{institution.name}}
{% endif %}
{% if institution.all.id == institution.parent_institution.id %}
{{institution.name}}
{% endif %}
{% for child in institutions.all %}
{% if child.id == institution.parent_institution.id %}
{{institution.name}}
{% endif %}
{% endfor %}
# views.py
class InstitutionDetail(DetailView):
model = Institution
def get(self, request, *args, **kwargs):
institutions_child = Institution.objects.filter(parent_institution__isnull=True).prefetch_related('parent_institution_set')
institutions = get_object_or_404(Institution, pk=kwargs['pk'])
context = {'institutions_child': institutions_child, 'institutions': institutions}
return render(request, 'stakeholders/institution_detail.html', context)
{% for child_node in institutions.parent_institution_set.all %}
{{child_node.name}}
{% endfor %}

我要么得到"无",要么得到当前机构名称(A(。

有人知道我如何才能实现让所有儿童机构都进入细节视图的目标吗?

感谢您的帮助!:(

相反方向的外键返回查询集,而不是模型实例。

<p><b>Child institution: </b></p>
<ul>
{% for child in institutions.child.all %}
<li>{{ child.name }}</li>
{% endfor %}
</ul>

最新更新