Hay all, i have a simple model like this
def Article(models.Model):
upvotes = models.ManyToManyField(User, related_name='article_upvotes')
downvotes = models.ManyToManyField(User, related_name='article_downvotes')
def votes(self):
return self.upvotes - self.downvotes
With the view i can do things like
article_votes = article.votes
Am i able to order by the votes function? Something like
article = Article.objects.order_by('votes')
EDIT
I’m not near my dev system at the moment, so the syntax might be a little off.
You can sort the list after the query returns the results:
sortedtakes a list and sorts it. You can provide a custom function that takes an element and returns the value to use when comparing elements.lambda a: a.votes()is an anonymous function that takes an article and returns the number of votes on the article.If you are going to retrieve all the articles anyway, there’s no downside to this solution. On the other hand, if you wanted only the top 10 articles by votes, then you’re pulling all the articles from the db instead of letting the db do the sort, and only returning the top ten. Compared to a pure SQL solution, this is retrieving much more data from the database.