Hey I want to sort objects based on a computed value in django… how do I do it?
Here is an example User profile model based on stack overflow that explains my predicament:
class Profile(models.Model):
user = models.ForeignKey(User)
def get_reputation():
...
return reputation
reputation = property(get_reputation)
So, say I want to sort users by reputation. How do I do that? I know you can’t just do this:
Profile.objects.order_by("-reputation")
Thanks for your help everyone 🙂
If you need to do the sorting in the database (because you have lots of records, and need to e.g. paginate them), the only real option is to turn reputation into a denormalized field (e.g. updated in an overridden
save()method on the model).