How to read part of many-to-many field in the template

11 views
Skip to first unread message

alghafli

unread,
Jun 15, 2014, 9:33:44 AM6/15/14
to django...@googlegroups.com
Hello django users. I am working on my first django project and I faced a little problem.
I have a library database with books. A book element may have several authors.
In the view function I query the database for books. I want to show the first three authors. I was thinking to do something similar to the following python code but using the template language:

authors_to_show = book.authors.get_queryset() [0:3]
for author in authors_to_show:
    #html code here


However, it appears that I cannot define variables in the template unless I extend the language a bit. Note that I have several books to process and I can do that using the for loop in the template language. But I want to ignore some authors in each book.
Any idea of a proper way to do this.

Thank you in advance,
Mohammad

Elliot Bradbury

unread,
Jun 15, 2014, 9:39:26 AM6/15/14
to django...@googlegroups.com
Hi Mohammad,

Check out slice.

It's a builtin template filter that can be used like this:

{% for author in book.authors.all|slice:"3" %}
  {# HTML up in here #}
{% endfor %}

Good luck,
Elliot


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/539DA033.4060100%40gmail.com.
For more options, visit https://groups.google.com/d/optout.

alghafli

unread,
Jun 15, 2014, 10:04:52 AM6/15/14
to django...@googlegroups.com
Thank you for the fast reply. I did what you suggested and it worked fine :)
Reply all
Reply to author
Forward
0 new messages