Django:计算外键并显示

时间:2018-07-20 14:20:54

标签: django count foreign-keys

假设我的数据库中有两个表,

  1. 可预订的桌子,具有3个属性( id book_name writer_id (外键))< / p>

  2. 可写入表格,具有2个属性( id writer_name

我想通过计算 booktable

显示作者姓名和该作家有多少本书

书桌

---------------------------------------
|   id   |   book_name   |  writer_id |
|-------------------------------------|
|    1   |   abc         |      2     |
|    2   |   bcd         |      1     |
|    3   |   efg         |      1     |
|    4   |   htj         |      2     |
|    5   |   klm         |      1     |
|    6   |   nop         |      3     |
|-------------------------------------|

作家表

----------------------------
|   id   |   writer_name   |
|---------------------------
|    1   |     xyz         |
|    2   |     bcb         |
|    3   |     eld         |
|    4   |     ccb         |
|---------------------------

so, 
  id 1 = 3 books
     2 = 3 books
     4 = 0 books

如何在html模板中显示。这是我的代码,

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 %}

2 个答案:

答案 0 :(得分:2)

您可以通过以下方式注释查询集:

def getwriters(request):
    wrt = writer.objects.annotate(
        numbooks=Count('book')
    )
    return render(request, "writers.html", {"wrt":wrt})

这将为每个 writer对象添加一个额外的属性numbook,其中包含与相关的书籍的数量(因此,在这种情况下,由那个作家)。

然后可以将其呈现为:

{% for p in wrt %}  
    <tr>
        <td>{{ p.writer_name }}</td>
        <td>{{ p.numbooks }}</td>
    </tr>
{% endfor %}

答案 1 :(得分:2)

您可以执行以下操作:

book.objects.filter(writer_pk=1).count()

这将返回所有作者为pk为1的图书的计数