On Monday, 13 July 2015 01:50:11 UTC+1, Andrea wrote:
>
> Hello. I'm new to both django and python. Been trying to figure out how to 
> group items from  a model for hours now. 
>
> This in an example code i made up to illustrate my problem:
> # Models
> class Book(models.Model):
>     submitted_by = models.ForeignKey(settings.AUTH_USER_MODEL, 
> related_name='book_subby')
>     submitted_date = models.DateField(auto_now=True)
>     book_title = models.CharField(max_length=200)
>     book_publisher = models.ForeignKey(Publishers)
>
> class Publishers(models.Model):
>     submitted_by = models.ForeignKey(settings.AUTH_USER_MODEL, 
> related_name='publisher_subby')
>     submitted_date = models.DateField(auto_now=True)
>     book_publisher = models.CharField(max_length=200)
>
> # View
> def book_list(request):
>     books = Book.objects.filter(submitted_by=request.user, 
> submitted_date__lte=timezone.now()).order_by('submitted_date')
>
>     return render(request, 'book/list_books.html', {
>         'books': books 
>         })
>
> # Template list_books.html
> {% for book in books %}
>     <ul> {{ book.book_publisher }}
>     <li> {{book.book_title }} </li>
> {% endfor %}
>
> This displays:
>
> Publisher X
> * Book A
> Publisher Y
> * Book B
> Publisher X
> * Book C
> Publisher Y
> * Book D
>
> I want to display:
> Publisher X
> * Book A
> * Book C
> Publisher Y
> * Book B
> * Book D
>
> I tried doing multiple for loops in the template, but couldn't make it 
> work.
> I would appreciate it alot if someone could nudge me in the right 
> direction on how to solve this. 
> Thanks, Andrea
>


There are several ways of doing this. One is to sort by Publisher first: 

    books = 
Book.objects.filter(...).select_related('book_publisher').order_by('book_publisher__book_publisher',
 
'submitted_date')

and use the {% ifchanged %} tag to only print the publisher name when it 
changes:

{% for book in books %}
    {% ifchanged %} {{ book.book_publisher }} {% endif changed %}
    <li> {{book.book_title }} </li>
{% endfor %}


--
DR.

-- 
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+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@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/d6249df1-3566-4fa3-82c6-fc49b52e56cb%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to