I used related_name in a Django template to look the foreign key record, and call the count method. Because I have so many "Main" record, the for loop inside the template will create too many queries to the database. If there an easy way for me to reduce the number of queries to the database? Please see below for my setup.
# 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 %}
Copyright Notice:Content Author:「user1187968」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/37958296/django-reduce-the-number-of-queries-in-orm