📜 ⬆️ ⬇️

django-voting sort by rating

I think many are familiar with this extension, but still:
django-voting allows you to enter an assessment of any entity on the digg-principle (+ 1 / -1) in a maximum of 30 minutes (taking into account the inclusion of asynchronous JS requests).
Project site: django-voting.googlecode.com
But there is one bad feature: the inability to sort entities by rating using standard ORM tools. Further I will describe how I implemented it.
In fact, the rating is retrieved by the query:
  SELECT SUM (vote) FROM votes WHERE content_type_id =?  AND object_id =? 
Where you should specify the type id (contenttype framework) and object id.
Of course, you can go to the forehead and do something like:
  Article.objects.extra (select = {'score': 'SELECT SUM (vote) FROM votes WHERE content_type_id =? AND object_id =?'}) 
But it is, IMHO, a bit long, especially if you need to do this many times.
“Many times” symbolizes the need to use managers ... Let's say Article.objects is the manager. Knowing this, you can write your own. The only question is how to determine the type id? This is the contenttype task of the framework. I think it's easier to give the manager code:
  class ScoreOrderManager (models.Manager):
     def select_score (self):
         "" "Select the voting results for the object" ""
         from django.contrib.contenttypes.models import ContentType
         model_type = ContentType.objects.get_for_model (self.model)
         table_name = self.model._meta.db_table
         return self.extra (select = {'score': 'SELECT SUM (vote) FROM votes WHERE content_type_id =% i AND object_id =% s.id'% (int (model_type.id), table_name)}) 
Next, we connect the manager to the object by simply adding a property (you can override objects) with the value = manager instance.
  class Article:
     title = models.CharField (max_length = 200)
     ...
     mymanager = ScoreOrderManager () 
Further, everything works according to the principle:
  Article.mymanager.select_score (). Order_by ('- score') 
The only problem is that select_score needs to be called directly from the manager. QuerySet has no such property. (I am ready to listen to suggestions on this matter)

Original: " django-voting sorting by rating "

PS> In general, on google code there is enough amount of django- * projects. I strongly advise you to see them, you will save a lot of strength. This I mean that I discovered them relatively recently.

')

Source: https://habr.com/ru/post/19927/


All Articles