3

I'm using django-simple-ratings on my project. I hook the ratings to my Post app, so users can vote up/down and then order it by the score. Pretty much what i want is included on the ratings app. There's this page where i need to list all of the Post (just like stackoverflow). But for every post in Post where i display the ratings, it hit the db, and it makes the site reeeaaall slow. models.py:

from ratings.models import Ratings, RatedItemBase

class PostRatings(RatedItemBase):

    content_object = models.ForeignKey('Post')

class Post(models.Model):

    title = models.CharField(max_length = 200)
    content = models.TextField()
    ratings = Ratings(PostRatings)

for q in Post.objects.all():
    print q.ratings.cumulative_score()
    #or
    print q.postratings_set.aggregate(Sum('score'))['score__sum']

For every loop, it hit the db, another try:

for q in Post.objects.prefetch_related('postratings_set'):
    print q.postratings_set.aggregate(Sum('score'))['score__sum']

Still hit the db for every loop.

Does any of you have the same problem? How did you solved it? Or should i change to another ratings app? Thank you.

Srikar Appalaraju
  • 71,928
  • 54
  • 216
  • 264
Faris Nasution
  • 3,450
  • 5
  • 24
  • 29

1 Answers1

1

I suspect there might be JOIN type queries with the absence of proper indexes. But you need to post or inspect what queries are actually getting executed by Django ORM. Only then can there a solution emerge for optimization. For this there is a perfect tool Django-debug.

After installing this app, you can use debugsqlshell. Running your models in this mode outputs the SQL that gets executed as you work in the Python interactive shell. For Example -

$ ./manage.py debugsqlshell
Python 2.6.1 (r261:67515, Jul  7 2009, 23:51:51)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from page.models import Page
>>> ### Lookup and use resulting in an extra query...
>>> p = Page.objects.get(pk=1)
SELECT "page_page"."id",
       "page_page"."number",
       "page_page"."template_id",
       "page_page"."description"
FROM "page_page"
WHERE "page_page"."id" = 1

Hope this helps...

Srikar Appalaraju
  • 71,928
  • 54
  • 216
  • 264