繁体   English   中英

打印一个有一个以上房屋的人的清单,每个房屋有一个以上电话号码

[英]printing a list of persons with more than one home, each home with more than one phone number

我有一类人,可以有多个房屋,每个房屋有一个或多个电话号码。

我已经定义了类,但是现在我试图创建一个列出每个人的视图,列出每个人的所有住所以及每个住所地址的所有电话号码……例如:

john smith
123 fake str
  305-99-8877
  305-99-8876
321 oak road
  444-98-7654

peter guy
453 north ave...

到目前为止,我有这样的事情:

(在我的views.py上)

def ViewAll(request):
  people = Person.objects.all()
  render_to_response('viewall.html', {'people': people})

(以及我的模板上)

{% 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 %}

关于如何写我的想法不见了吗? 当然,如果有另一种方式(更好,更优雅或更有效的方式)来做我需要的事情,我很想听听。

您似乎拥有三个嵌套的集合:“人”,“家”,“电话号码”。

第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

不要忽略这一步。 如果您无法使其在视图函数中工作,则您的模型是错误的。 花点时间把这部分做好。

步骤2-将其转换为模板语法。

{% for p on people %}
    {% for h in p.home_address_set.all %}
        {% fpr ph in h.phone_set.all %}
        {% endfor %}
    {% endfor %}
{% endfor %} 

结果应与您的视图功能相同。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM