嘿!:)
我有一個模型來創建單個機構 ( Institution) 并且可以通過parent_institution(self)將其連接到父機構。
所以我有機構A,它是b, c, d 的父級(所有它們都是具有自己詳細視圖的單一機構。)在b的詳細資訊視圖中,我有“父機構”部分,結果我得到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",
)
通常我可以通過這個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 %}
我要么得到 None 要么得到當前的機構名稱 (A)。
有誰知道我如何實作在詳細視圖中顯示所有兒童機構的目標?
任何幫助表示贊賞!:)
uj5u.com熱心網友回復:
相反方向的外鍵回傳一個查詢集,而不是一個模型實體。
<p><b>Child institution: </b></p>
<ul>
{% for child in institutions.child.all %}
<li>{{ child.name }}</li>
{% endfor %}
</ul>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/371705.html
標籤:姜戈 django 模型 django-模板 外键 亲子
上一篇:如何將資料庫資料顯示到您的網站?
