finally{}

all will be well finally

Handling ManyToMany field in Django

with one comment

I’m still learning Django; but as I learn more and more I admire the thoughtfulness of those who designed the framework. They’ve surely made complex things easy and simple things easier.

I continue to learn Django by creating applications that I will use – either at office or at home. First I created SOL (a microblog) to be used at office; Now I’m developing a book inventory application for my own use.

In this application, I have a M2M model – book and authors.

class Author(models.Model):
    name = models.CharField(max_length=45)


class Book(models.Model):
    ...
    authors = models.ManyToManyField(Author, verbose_name="Authors")
    ...

Django’s Many-to-Many relation documentation is pretty detailed. I couldn’t find much details on using M2M in a template. However, it was explained in Google Group.

<p>{% for item in query_list %}        <tr class="itemrow">
    <td class="itemcol"> {{item.title}}            
  </td><td class="itemcol">
     {% for author in item.authors.all %} <br />          
         {{author.name}}
     {%endfor %}</td></tr>
{% endfor %}</p>

If you are implementing AJAX, you may want to compile the rows into a list. That can be achieved by:

rows = [{'id': book.id,
       'cell': [book.title, ' &amp; '.join([auth.name for auth in book.authors.all()]), book.publisher, book.isbn]} for book in books]

Don’t know if that’s all to M2M. But this all I’ve learnt.

Related Posts:

Written by Joseph Jude

May 24th, 2008 at 11:40 pm

Posted in Programming

Tagged with

One Response to 'Handling ManyToMany field in Django'

Subscribe to comments with RSS or TrackBack to 'Handling ManyToMany field in Django'.

  1. Thanks for this. I have working through the Django book and had been struggling how to get the many-to-many to work.

    Thanks!

    Matthew

    24 Jun 08 at 12:46 am

Leave a Reply