Custom Search

Thursday, April 8, 2010

how to print ManyToMany Field value in Template in django

how to print ManyToMany Field value in Template in django
==================================

{{book.author}} print some thing like

how get author name?
its a many-to-many field
so you have to do
book.author.all()
also, you have to change the related name to authors
so that it becomes book.authors.all()

====================================

Example

------------------- models
class Book(models.Model):
library = models.ForeignKey(Library)
accession_no = models.CharField(max_length=200, blank=True, null=True)
type = models.CharField(max_length=500, blank=True, null=True)
author = models.ManyToManyField('Contributor', related_name='book_authors')
editor = models.ManyToManyField('Contributor', blank=True, null=True, related_name='book_editors')
reviser = models.ManyToManyField('Contributor', blank=True, null=True, related_name='book_revisers')


class Contributor(models.Model):
library = models.ForeignKey(Library)
name = models.CharField(max_length=1000)

def __unicode__(self):
return self.name

class Meta:
ordering = ('name',)

------------------- template

{{book.author.all.0}}
{{book.editor.all.0}}
{{book.reviser.all.0}}


-------------------

No comments:

Post a Comment