gpt4 book ai didi

python - 在 Django 模板中计算外键模型的正确方法

转载 作者:太空宇宙 更新时间:2023-11-04 03:24:56 25 4
gpt4 key购买 nike

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

class Article(models.Model):
author = models.ForeignKey(Author)

假设我需要在模板中显示有多少 Articles 来自确定的作者。这是 View :

def myview(request):
context = {
'authors': Author.objects.all()
}

只需执行 {{ author.Articles||length }} 就需要我编辑 Author 模型。如果这是正确的方法(显然不是),我应该在 models.py 级别还是在 View myview 中执行此操作?

我相信在 models.py 中编辑模型会导致非常糟糕的代码设计。

myview 中这样做需要我做这样的事情:

authors = []
for author in authors:
count = Article.objects.filter(author__exact=author).count()
authors.append(author, count)
horrendously_bad_code_design_context = {
'authors': authors,
}

这样做的正确方法是什么?我认为这两种实现都非常糟糕且“hacky”。​​

最佳答案

如果你已经有一个检索到的作者并且你想获得文章计数然后使用 related manager's count 方法 (author.article_set.count()) 可能没问题。

另一方面,如果您正在迭代(可能很大)Author 查询集只是为了获取计数,它会执行大量查询(一个检索所有作者,一个检索每个作者得到计数)。这可以很容易地替换为 annotated queryset这只会导致一个查询:

from django.db.models import Count

Author.objects.annotate(article_count=Count('articles'))

稍后在您的模板中,您可以使用 {{ author.article_count }}

关于python - 在 Django 模板中计算外键模型的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33426524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com