DUPLICATE: http://stackoverflow.com/questions/981375/using-a-django-custom-model-method-property-in-orderby
I have two models; one that stores posts and another that stores votes made on those posts, related using a ForeignKey field. Each vote is stored as a separate record since I need to track the user and datetime that the vote was cast.
I've created a helper function that tallys all the votes using the Django 1.1 aggregation Sum function.
class Post(models.Model):
...some fields...
def tally(self):
return self.vote_set.all().aggregate(Sum('value'))['value__sum'] or 0
class Vote(models.Model):
post = models.ForeignKey(Post)
value = models.IntegerField()
...some fields...
One query I need to make needs to do a one off order_by
of the tally. However:
Post.objects.all().order_by('tally')
yields the following template error:
Caught an exception while rendering: Cannot resolve keyword 'tally' into field. Choices are: date_created, description, id, is_active, name, related, slug, user, vote
It there any way to get the order_by()
function to take a callable?