Joseph Jude

Handling ManyToMany field in Django

2008.05.24 / code / python / django /

Sample code to handle M2M in Django

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.

{% for item in query_list %}


{{item.title}}

{% for author in item.authors.all %}

       {{author.name}}
   {%endfor %}</td></tr>

{% endfor %}

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, ‘ & ‘.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 learned.


Share this post on

Twitter | | |
Sign up for my weekly newsletter

I will send blog updates to this email. You can unsubscribe at any time using the link in those emails.