views:

27

answers:

1

Is there a way to specify a value from a list of one-to-many models at Django's Template?

For example I can do this in the shell: author.book_set.get(publisher=my_publisher). However I want something like that in my template. I'm only passing Authors, a list of Author and publisher to the template.

Models:

class Publisher(models.Model):
    name = models.CharField(max_length=30)

class Author(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)

class Book(models.Model):
    title = models.CharField(max_length=100)
    authors = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher)
    publication_date = models.DateField(blank=True, null=True)
    num_pages = models.IntegerField(blank=True, null=True)

Template:

{% for author in authors %}
    {{ author.book_set.get(publisher=publisher) }}<br/>   {% comment %} this is the part that needs to be corrected {% endcomment %}

{% endfor %}
+2  A: 

I'm not sure if it can be done in the template. You could add an extra property on the author in the view, like so:

for author in authors:
    author.relevant_books = author.book_set.get(publisher=publisher)
Rasmus Kaj