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).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.
Project site: django-voting.googlecode.com
SELECT SUM (vote) FROM votes WHERE content_type_id =? AND object_id =?Where you should specify the type id (contenttype framework) and object id.
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.
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)
Source: https://habr.com/ru/post/19927/
All Articles