sample views.py tell me how to write code, thanks in advance

def articles(request, article_id): queryset = Article.objects.all() comments_sum = Comments.objects.values('comments_article_id').count() return render_to_response('articles.html', {'articles': queryset, 'article1': comments_sum}) 

models.py

 from django.db import models class Article(models.Model): class Meta: db_table = "article" article_title = models.CharField(max_length=100) article_text = models.TextField() article_date = models.DateTimeField() article_likes = models.IntegerField(default=0) article_comment_sum = models.IntegerField(default=0) def __str__(self): return self.article_title class Comments(models.Model): class Meta: db_table = "comments" comments_text = models.TextField(verbose_name='Поле комментария') comments_article = models.ForeignKey(Article, on_delete=models.CASCADE) article_comments_sum = models.IntegerField(default=0) def __str__(self): return self.comments_text 
  • Show the model code. - Sergey Gornostaev

1 answer 1

The article_comment_sum fields article_comment_sum not needed. Simply annotate the QuerySet result of an aggregate function :

 articles = Articles.objects.annotate(comments_count=Count('comments_set')).all() 

PS Name the model taken in the singular

  • I apologize, but what about the 'comments_set' field, I recently studied django and I do not really understand it yet. writes error: Cannot resolve keyword 'comments_set' - xxx xxx
  • This is the reverse relation that ORM creates if another model refers to a model. Error should not occur. - Sergey Gornostaev
  • no, he accepted only Count ('comments'), and Count ('comments_set'), cursed that there was no such Cannot resolve keyword 'comments_set' - xxx xxx
  • So you have the relative_name attribute in the ForeignKey . - Sergey Gornostaev
  • class Comments (models.Model): class Meta: db_table = "comments" comments_text = models.TextField (verbose_name = 'Comment field') comments_article = models.ForeignKey (Article, on_delete = models.CASCADE) article_comments_sum = models.IntegerField (default) = 0) def __str __ (self): return self.comments_text - xxx xxx