Reputation: 33
Suppose I have two table in my database,
booktable which have 3 attributes (id, book_name, writer_id(foreignkey))
writertable which have 2 attributes (id, writer_name)
I want to display writer name and how many books have that writer by calculate booktable
book table
---------------------------------------
| id | book_name | writer_id |
|-------------------------------------|
| 1 | abc | 2 |
| 2 | bcd | 1 |
| 3 | efg | 1 |
| 4 | htj | 2 |
| 5 | klm | 1 |
| 6 | nop | 3 |
|-------------------------------------|
Writer table
----------------------------
| id | writer_name |
|---------------------------
| 1 | xyz |
| 2 | bcb |
| 3 | eld |
| 4 | ccb |
|---------------------------
so,
id 1 = 3 books
2 = 3 books
4 = 0 books
How can I display in html template. Here is my code,
models.py
class book(models.Model):
book_name = models.CharField(max_length = 100)
writer = models.ForeignKey(writer, on_delete = models.CASCADE)
class writer(models.Model):
writer_name = models.CharField(max_length = 100)
def __str__(self):
return self.writer_name
view.py
def getwriters(request):
wrt = writer.objects.all()
return render(request, "writers.html", {"wrt":wrt})
writers.html
{% for p in wrt %}
<tr>
<td>{{ p.writer_name }}</td>
<td>{{**Should display how many books have this writer**}}</td>
</tr>
{% endfor %}
Upvotes: 3
Views: 3292
Reputation: 476584
You can annotate the queryset with:
def getwriters(request):
wrt = writer.objects.annotate(
numbooks=Count('book')
)
return render(request, "writers.html", {"wrt":wrt})
This will add to every writer
object an extra attribute numbook
that contains the number of related books (so in this case books written by that writer).
You can then render it as:
{% for p in wrt %}
<tr>
<td>{{ p.writer_name }}</td>
<td>{{ p.numbooks }}</td>
</tr>
{% endfor %}
Upvotes: 2
Reputation: 4635
You can do something like this :
book.objects.filter(writer_pk=1).count()
This will return count of all books with writer whose pk is 1
Upvotes: 0