我在Django模板中使用了related_name来查看外键记录,并调用count方法。因为我有这么多“Main”记录,所以模板中的for循环会对数据库创建太多查询。如果有一种简单的方法可以减少对数据库的查询次数?请参阅下面的设置。
# models.py
class Main(models.Model):
name = models.CharField(_('Name'), max_length=255)
class Sub1(models.Model):
main = models.ForeignKey(Main, on_delete=models.CASCADE)
name = models.CharField(_('Name'), max_length=255)
class Sub2(models.Model):
main = models.ForeignKey(Main, on_delete=models.CASCADE)
name = models.CharField(_('Name'), max_length=255)
class Sub3(models.Model):
main = models.ForeignKey(Main, on_delete=models.CASCADE)
name = models.CharField(_('Name'), max_length=255)
# views.py
def get_main(request):
main_list = Main.objects.all()
...
# template
{% for main in main_list %}
{{main.sub1_set.count}}
{{main.sub2_set.count}}
{{main.sub3_set.count}}
{% endfor %}
答案 0 :(得分:2)
您可以使用annotations在一个查询中执行此逻辑:
from django.db.models import Count
def get_main(request):
main_list = Main.objects.all().annotate(sub1_count=Count('sub1', distinct=True),
sub2_count=Count('sub2', distinct=True),
sub3_count=Count('sub3', distinct=True))
然后在模板中:
{% for main in main_list %}
{{ main.sub1_count }}
{{ main.sub2_count }}
{{ main.sub3_count }}
{% endfor %}
(编辑:已添加distinct
)