Is it possible to order_by with a callable?
DUPLICATE: Using a Django custom model method property in order_by()
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 si开发者_开发问答nce 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?
It turns out the Annotate method was the solution:
Post.objects.all().annotate(vote_tally=Sum('vote__value')).order_by('-vote_tally')
精彩评论