我有4个模型需要彼此通过链继承来呈现。 像这样:
├───GRANDPARENT1
│ ├───PARENT11
│ │ ├───CHILD111
│ │ └───CHILD112
│ └───PARENT12
│ ├───CHILD121
│ └───CHILD122
└───GRANDPARENT2
├───PARENT21
│ ├───CHILD211
│ └───CHILD212
└───PARENT22
├───CHILD221
└───CHILD222
我可以像描述here一样,在单个模板中通过多个{%for%}循环来做到这一点:
{% for grandparent in grandparents %}
<p>{{ grandparent.title }}'s childs is:</p>
{% for parent in grandparent.parent_set.all %}
<p>{{ parent.title }}'s childs is:</p>
{% for child in parent.child_set.all %}
<p>{{ parent.title }}</p>
{% endfor %}
{% endfor %}
{% endfor %}
但是我想将每个类划分到它自己的模板上,并将它们带入相同的形式,以使内容更加清晰和易于添加随后的更多嵌套级别。
我将展示两个模型来说明问题所在-父母和孩子:
我尝试从base.html扩展父模板-可以。但是接下来,当我从parent.html扩展child.html模板时,它什么也不输出。
models.py:
class Parent(models.Model):
title = models.CharField(
max_length=150,
)
class Child(models.Model):
title = models.CharField(
max_length=150,
)
parents = models.ManyToManyField(
Parent,
blank=True
)
更新2
在数据库中,我有两个父类的对象(PARENT1,PARENT2)和四个子类的对象(CHILD11,CHILD12,CHILD21,CHILD22)。 CHILD11和CHILD 12在父母多对多关系中具有PARENT1; CHILD21和CHILD22在PARENT2上具有相同的结构,因此具有以下结构:
├───PARENT1
│ ├───CHILD11
│ └───CHILD12
└───PARENT2
├───CHILD21
└───CHILD22
views.py:
class ParentListView(ListView):
model = Parent
template_name = 'parent_list.html'
context_object_name = 'parent_objects_list'
class ChildListView(ListView):
model = Child
template_name = 'child_list.html'
context_object_name = 'child_objects_list'
urls.py
from django.urls import path
from .views import (
ParentListView,
ChildListView
)
urlpatterns = [
path('parents/', ParentListView.as_view(), name='parents'),
path('childs/', ChildListView.as_view(), name='childs'),
]
parent_list.html(已更新):
{% extends '_base.html' %}
{% block title %}Parents_list{% endblock title %}
{% block content %}
{% for parent in parent_objects_list %}
<div class="card">
<div class="card-header">
<span class="font-weight-bold">{{ parent.title }}</span>
</div>
<div class="card-body">
{% block childs_block %}
{% endblock childs_block %}
</div>
</div>
{% endfor %}
{% endblock content %}
child_list.html
{% extends 'parent_list.html' %}
{% block title %}Childs_list{% endblock title %}
{% block childs_block %}
{% for child in child_objects_list %}
<div class="card">
<div class="card-header">
<span class="font-weight-bold">{{ child.title }}</span>
</div>
</div>
{% endfor %}
{% endblock childs_block %}
-返回空。我认为我需要将带有key的参数传递给childs块以过滤某些父级的childs,但找不到解决方法。
答案 0 :(得分:1)
您的Site Styles
仅发送ChildListView
的查询。因此,这意味着在渲染模板时没有child_objects_list
,因此parent_objects_list
循环不会循环。
因此,您可以在{% for ... %}
中传递Parent
对象的列表,最好在ChildListView
模型上使用prefetch_related
:
child
然后您可以遍历class ChildListView(ListView):
model = Parent
template_name = 'child_list.html'
context_object_name = 'parent_objects_list'
queryset = Parent.objects.prefetch_related('child')
:
child_set