Django: related_name поля ForeignKey, связанного с самим собой, не работает | получаем противоположное направление ссылки на себя в шаблоне
Hej! :)
У меня есть модель для создания отдельных учреждений (Institution
) и я могу соединить его с родительским учреждением, через parent_institution
(self).
Итак, у меня есть учреждение A, которое является родительским для b, c, d (Все сами по себе отдельные учреждения с собственным детальным представлением. ) В подробном представлении b у меня есть раздел 'parent institution', где я получаю A как результат, включая ссылку на подробное представление A.
<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",
)
обычно я могу следовать за ForeignKey в обратном направлении через это related_name.
<p><b>Child institution: </b>
{{institution.child.name}}
</p>
но в данном случае это не работает и выдает "None". Поэтому я попробовал:
{% 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 %}
Я получаю либо None, либо имя текущего учреждения (A).
Кто-нибудь знает, как я могу достичь цели получения всех дочерних учреждений в детальном представлении?
Любая помощь будет принята с благодарностью! :)
Внешний ключ в обратном направлении возвращает набор запросов, а не экземпляр модели.
<p><b>Child institution: </b></p>
<ul>
{% for child in institutions.child.all %}
<li>{{ child.name }}</li>
{% endfor %}
</ul>