[英]printing a list of persons with more than one home, each home with more than one phone number
I have a class Person which can have several Homes, each one with one or many Phone numbers. 我有一类人,可以有多个房屋,每个房屋有一个或多个电话号码。
I have defined the classes, but now i am trying to create a view wich list every person, with all its homes and all the phone numbers for each home address... something like: 我已经定义了类,但是现在我试图创建一个列出每个人的视图,列出每个人的所有住所以及每个住所地址的所有电话号码……例如:
john smith
123 fake str
305-99-8877
305-99-8876
321 oak road
444-98-7654
peter guy
453 north ave...
so far i have something like this: 到目前为止,我有这样的事情:
(on my views.py) (在我的views.py上)
def ViewAll(request):
people = Person.objects.all()
render_to_response('viewall.html', {'people': people})
(and on my template) (以及我的模板上)
{% 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 %}
any idea of how to write the for I'm missing? 关于如何写我的想法不见了吗? of course, if there is another way (a better more elegant or efficient way) of doing what I need, I would love to hear it.
当然,如果有另一种方式(更好,更优雅或更有效的方式)来做我需要的事情,我很想听听。
You have what appears to be three nested collections: Person, Home, Phone Number. 您似乎拥有三个嵌套的集合:“人”,“家”,“电话号码”。
Step 1 - How would you write this in a view function? 第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
Don't omit this step. 不要忽略这一步。 If you can't make it work in a view function, your model is wrong.
如果您无法使其在视图函数中工作,则您的模型是错误的。 Take the time to get this part right.
花点时间把这部分做好。
Step 2 - Convert this into template syntax. 步骤2-将其转换为模板语法。
{% for p on people %}
{% for h in p.home_address_set.all %}
{% fpr ph in h.phone_set.all %}
{% endfor %}
{% endfor %}
{% endfor %}
The results should be the same as your view function. 结果应与您的视图功能相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.