book count per author for filtered book list

67 views
Skip to first unread message

Владислав Максимов

unread,
May 8, 2011, 9:37:30 AM5/8/11
to django...@googlegroups.com

Hi! Short question. I have two models:

class Author(models.Model):
    name
= models.CharField(max_length=250)

class Book(models.Model):
    title
= models.CharField(max_length=250)
    author
= models.ManyToManyField(Author)

One view:

def filter_books(request):
    book_list
= Book.objects.filter(...)

How can I display in template next content:

Authors in selected books:
   
Author1: book_count
   
Author2: book_count
   
...

http://stackoverflow.com/q/5927251/604789

Oleg Lomaka

unread,
May 8, 2011, 1:05:51 PM5/8/11
to django...@googlegroups.com
I would do this via intermediate model, 

class Author(models.Model):
    name = models.CharField(max_length=250)
class Book(models.Model):
    title = models.CharField(max_length=250)
    author = models.ManyToManyField(Author, through="BookAuthor")
class BookAuthor(models.Model):
    author = models.ForeignKey(Author)
    book = models.ForeignKey(Book)

def filter_books(request):
    book_list
= Book.objects.filter(...)
    BookAuthor.objects.filter(book__in=book_list).values('author').annotate(books_num=models.Count('author'))
You'll get a list of dicts with authors' PKs and book_num int.





--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django...@googlegroups.com.
To unsubscribe from this group, send email to django-users...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

Reply all
Reply to author
Forward
0 new messages