views:

68

answers:

1

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

+2  A: 

In order to add extra information, you should use a ManyToMany relationship with a 'trough' extra-field : http://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships

This will lead to this code:

def contact_view_full(request, contact_id):
    c = get_object_or_404(Contact, id=contact_id)
    a = c.addresses.all()
    return render_to_response('contact_full.html', {'contact_item': c, 'addresses' : a }, context_instance=RequestContext(request))
Pierre-Jean Coudert
That looks like exactly what I need. Thanks!
Ninefingers