There are 2 models:

class shops_cafe(models.Model): cafe_name = models.CharField(max_length=255, unique=True, verbose_name="Название", help_text="Название") cafe_status = models.NullBooleanField(verbose_name="Статус", blank=True, default=None) cafe_like = models.IntegerField(default=0, verbose_name="Лайки", null=True, blank=True) cafe_added = models.ForeignKey(AuthUser, verbose_name="Добавил", null=True, blank=True) cafe_logo = models.ImageField(upload_to='cafe_logo', blank=False, null=False, default='cafe_logo/default_logo.jpg', verbose_name="Логотип", help_text="Логотип") cafe_info = models.CharField(max_length=1024, null=True, blank=True, verbose_name="Краткое описание", help_text="Краткое описание") cafe_web = models.URLField(null=True, blank=True, verbose_name="Веб-сайт", help_text="Веб-сайт") cafe_adres = models.CharField(max_length=512, verbose_name="Адрес", help_text="Адрес", null=True, blank=True) cafe_phone = models.CharField(max_length=50, null=True, blank=True, verbose_name="Номер телефона", help_text="Номер телефона") class Meta(): db_table = "Кафе/рестораны" def __str__(self): return self.cafe_name 

and

 class shops_cafe_com(models.Model): shc_create_date = models.DateTimeField(default=timezone.now(), verbose_name="Дата создания") shc_text = models.TextField(max_length=3000, verbose_name="Текст", help_text="Максимальная длина") shc_cafe = models.ForeignKey(shops_cafe, verbose_name="Кафе/ресторан") shc_create_name = models.ForeignKey(AuthUser, verbose_name="Добавил") class Meta(): db_table = "Кафе/рестораны_комментарии" 

apparently komenty-subsidiary, shops_cafe - parent.

In the view, I will organize everything through the paginator and into the template I draw the list (for ...) from the shops_cafe:

 def ...(request, page_number=1): ... all_cafe = shops_cafe.objects.filter(cafe_status="1").order_by('-cafe_like') current_page = Paginator(all_cafe, 3) args['cafes'] = current_page.page(page_number) return render_to_response("shops.html", args, context_instance=RequestContext(request)) 

accordingly, the template is already, for example, {{ cafe.cafe_name }} , etc.

Question: how can I get data from the child model? Those. required next to {{ cafe.cafe_name }} to bring the number of comments from shops_cafe_com

    1 answer 1

     from django.db.models import Count all_cafe = shops_cafe.objects.filter( cafe_status="1" ).annotate(shc_count=Count('shops_cafe_com')).order_by('-cafe_like') 

    In the template: {{ cafe.shc_count }} . Aggregation

    • Thank. It also works: (without changing the view) in the template {{cafe.shops_cafe_com_set.count}} - FlatOMG
    • one
      @FlatOMG If you use {{ cafe.shops_cafe_com_set.count }} , then for each cafe from all_cafe SQL query will be executed. If you use annotations, then 1 query will be executed. But this is optimization. - Vladimir Danilov