0

Im new to django and trying to learn with building a forum

my model

class Subject(models.Model):
    name=models.CharField(max_length=128)
    created=models.DateTimeField('Created Date')


    def __str__(self):
        return self.name

class Book(models.Model):
    book_subject=models.ForeignKey(Subject,on_delete=models.CASCADE)
    book_title=models.CharField(max_length=128)
    url=models.URLField()
    votes=models.IntegerField(default=0)


    def __str__(self):
        return self.book_title

my query to database in django shell

Subject.objects.all()
>>>[<Subject: electronics>, <Subject: compter science>]

q=Subject.objects.get(id=2)
q.book_set.all()
>>>[<Book: python django>, <Book: python flask>]

How should i get the number of books for each subjects. (to get count of books for electronics and computer science subjects) I know this could be straight forward answer. I wanted to show the template as in forum where it displays subject name and number of books it contains

Can someone help me with query to get number of books for each subjects

Any help is much appreciated..Thanks in advance

spidy
  • 269
  • 2
  • 13

1 Answers1

3

If you only need the number of books for a certain subject, there is count

Subject.objects.get(id=2).book_set.count()

If you need the subjects with a count for the number of books for them you can annotate

from django.db.models import Count
subjects = Subject.objects.annotate(num_books=Count('book'))

for subj in subjects:
    print subj.num_books 
Sayse
  • 42,633
  • 14
  • 77
  • 146
  • @Sayse..Im getting error "FieldError: Cannot resolve keyword 'books' into field. Choices are: book, created, id, name" – spidy Feb 12 '16 at 08:26
  • @AmoghAngadi - It should be `book` – Sayse Feb 12 '16 at 08:29
  • @AmoghAngadi - No worries, theres a link in my answer to the documentation for it – Sayse Feb 12 '16 at 08:39
  • @Sayse..How i can get the count of number of books separately for electronics and computer science? – spidy Feb 12 '16 at 08:51
  • @Sayse..your answer doesn't give separate count of 2 books.....help me please..... to get count of books for electronics and computer science – spidy Feb 12 '16 at 09:19
  • @AmoghAngadi - You've updated your question to be a different question, this answer does solve your original question, if you have another question then you should raise it as a separate question (with what you have tried/researched) – Sayse Feb 12 '16 at 09:24
  • @Sayse......I actually meant the same...but made changes to make things clear mate – spidy Feb 12 '16 at 09:27
  • 1
    @spidy This answer should give you what you want. If you want it in one object, try this: `Subject.objects.annotate(num_books=Count('book')).values('name', 'num_books')` – csinchok Feb 12 '16 at 19:04