Handling ManyToMany field 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.
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.
<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:
'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 learnt.
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