I have the following models:
class Question(models.Model):
Title = models.CharField(max_length=250)
User = models.ForeignKey(User)
def GetVotes(self):
return Vote.objects.filter(Question=self).aggregate(Sum('Vote'))['Vote__sum']
class Vote(models.Model):
Question = models.ForeignKey(Question)
User = models.ForeignKey(User)
Vote = models.IntegerField()
And as can be seen from the Question
model I use a custom method to calculate the votes for each question. I do that as I would like to separate the votes from the actual question, and hence I wouldn't want to keep a vote counter in the Question
model as well as in Vote
as this will be hard to maintain later.
According to good design, information that can be calculated shouldn't be stored.
I can now find the votes of each question just fine, but the problem comes down to the order_by
. I would like to get all the questions, and order them by their votes. As far as I am aware, that is not possible as the order_by()
is down to the database level, where my method is not at a database level.
I would like to find a nice way to do that without using other technique than ORM
is that possible?
Edit:
It looks like there is no nice way using ORM so I have implemented using sorted
.