Monday, March 7, 2011

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)

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.

From stackoverflow
  • You have what appears to be three nested collections: Person, Home, Phone Number.

    Step 1 - How would you write this in a view function?

    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.

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

0 comments:

Post a Comment