Django - provide additional information in template

Posted by Ninefingers on Stack Overflow See other posts from Stack Overflow or by Ninefingers
Published on 2010-03-22T21:42:16Z Indexed on 2010/03/22 21:51 UTC
Read the original article Hit count: 544

Hi all,

I am building an app to learn Django and have started with a Contact system that currently stores Contacts and Addresses. C's are a many to many relationship with A's, but rather than use Django's models.ManyToManyField() I've created my own link-table providing additional information about the link, such as what the address type is to the that contact (home, work etc). What I'm trying to do is pass this information out to a view, so in my full view of a contact I can do this:

def contact_view_full(request, contact_id):
    c = get_object_or_404(Contact, id=contact_id)

    a = []
    links = ContactAddressLink.objects.filter(ContactID=c.id)    
    for link in links:
        b = Address.objects.get(id=link.AddressID_id)
        a.append(b)

    return render_to_response('contact_full.html', {'contact_item': c, 'addresses' : a }, context_instance=RequestContext(request))

And so I can do the equivalent of c.Addresses.all() or however the ManyToManyField works. What I'm interested to know is how can I pass out information about the link in the link object with the 'addresses' : a information, so that when my template does this:

{% for address in addresses %}
<!-- ... -->
{% endfor %}

and properly associate the correct link object data with the address.

So what's the best way to achieve this? I'm thinking a union of two objects might be an idea but I haven't enough experience with Django to know if that's considered the best way of doing it. Suggestions?

Thanks in advance.

Nf

© Stack Overflow or respective owner

Related posts about django

Related posts about django-templates