I’m trying to sort a list of posts where votes have priority over the date.
I have my own app called UserPost and I’m using the django-voting app to do votes.
class UserPost(models.Model):
user = models.ForeignKey(User)
datetime = models.DateTimeField(auto_now_add=True)
text = models.CharField(max_length=255, blank=True)
is_deleted = models.BooleanField(default=False)
vote = models.ForeignKey(Vote)
Right now, I’m sorting without votes taking precedence yet:
posts_list = sorted(posts_list, key=attrgetter('datetime'))
What’s the best way to go about this?
Thanks!
Tuples are sorted lexicographically, therefore if you return a tuple for sorted’s key= argument you can sort by votes then by dates:
Alternatively, you might want to also look at the
orderingoption in a django Model’s Meta class or theorder_bymethod on django Queryset. They will do the sorting on the database in one query, so can be much faster. Alternatively, you can try the posts_list.get_score_in_bulk() to reduce the number of queries to two (one for posts_list, and one for get_score_in_bulk), like so: