Ero*_*San 1 python django django-templates
我有一个人类,可以有几个家庭,每个家庭有一个或多个电话号码.
我已经定义了这些类,但现在我正在尝试创建一个列出每个人的视图,包括所有家庭和每个家庭地址的所有电话号码......类似于:
john smith
123 fake str
305-99-8877
305-99-8876
321 oak road
444-98-7654
peter guy
453 north ave...
Run Code Online (Sandbox Code Playgroud)
到目前为止我有这样的事情:
(在我的views.py上)
def ViewAll(request):
people = Person.objects.all()
render_to_response('viewall.html', {'people': people})
Run Code Online (Sandbox Code Playgroud)
(在我的模板上)
{% for guy in people %}
{{ guy.name }}
{% if person.home_address_set.all %}
{{ home_address }}
{% for ?????? in ???? %}
#print phone numbers in each home
{% endfor %}
{% endif %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
任何关于如何写我错过的想法?当然,如果有另一种方式(一种更优雅或更有效的方式)做我需要的东西,我很乐意听到它.
你有三个嵌套的集合:人,家,电话号码.
第1步 - 你如何在视图函数中写这个?
for p in Person.objects.all():
print "person", p
for h in p.home_address_set.all():
print " home", h
for ph in h.phone_set.all():
print " phone", ph
Run Code Online (Sandbox Code Playgroud)
不要忽略此步骤.如果您无法在视图功能中使其工作,则您的模型是错误的.花点时间让这部分正确.
第2步 - 将其转换为模板语法.
{% for p on people %}
{% for h in p.home_address_set.all %}
{% fpr ph in h.phone_set.all %}
{% endfor %}
{% endfor %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
结果应与您的视图函数相同.
| 归档时间: |
|
| 查看次数: |
259 次 |
| 最近记录: |