Hi Sardor, Are you using PostgreSQL?
Simon Le lundi 16 mars 2015 05:19:38 UTC-4, Sardor Muminov a écrit : > > > > Hello there, > > > I am trying to perform aggregation from all objects which have one foreign > key. > > > These are my models: > > ... > > class Post(models.Model): > id = models.CharField(max_length=255, primary_key=True) > > > message = models.TextField() > created_time = models.DateTimeField(db_index=True) > updated_time = models.DateTimeField() > creator = models.ForeignKey(Member, db_index=True) > likes = models.IntegerField(db_index=True) > > > class Comment(models.Model): > id = models.CharField(max_length=255, primary_key=True, db_index=True) > message = models.TextField() > created_time = models.DateTimeField(db_index=True) > creator = models.ForeignKey(Member, db_index=True) > post = models.ForeignKey(Post, db_index=True) > likes = models.IntegerField(db_index=True) > > ... > > > And this is my query: > > top_commented_posts = Post.objects.annotate( > num_comments=Count('comment')).order_by('-num_comments')[:10] > > In my template, I iterate over top_commented_posts: > > ... > > {% for post in top_commented_posts %} > <tr> > <td>{{ forloop.counter }}.</td> > <td>{{ post.message | slice:"25"}}...</td> > <td>{{ post.num_comments }}</td> > <td><a class="btn btn-xs btn-inverse" href=" > https://www.mydomain.com/{{ post.id }}/" target="_blank"><span > class="icon-link"></span></a></td> > </tr> > {% endfor %} > > ... > > > This operations is one of the 27 ones from one page. > > Django debug toolbar result: > 5335.56 ms (27 queries) > > 26 each queries taking between 1.44ms (min) and 227ms (max). > > > Please, share your experience and advices on how can I optimize this query. > I have also attached Django debug toolbar screenshot. > > > Thanks in advance, > Sardor > -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/a6c163eb-c782-4ecf-9d56-c0039469bab7%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.