47👍
✅
Oh, of course I forget about new aggregation support in Django and its annotate
functionality.
So query may look like this:
Contest.objects.get(pk=id).image_set.annotate(score=Sum('vote__value')).order_by( 'score' )
9👍
You can write your own sort in Python very simply.
def getScore( anObject ):
return anObject.score()
objects= list(Contest.objects.get( pk = id ).image_set)
objects.sort( key=getScore )
This works nicely because we sorted the list, which we’re going to provide to the template.
- [Django]-Where does pip install its packages?
- [Django]-Startapp with manage.py to create app in another directory
- [Django]-RuntimeError: Model class django.contrib.sites.models.Site doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
2👍
The db-level order_by
cannot sort queryset by model’s python method.
The solution is to introduce score
field to Image
model and recalculate it on every Vote
update. Some sort of denormalization. When you will can to sort by it.
- [Django]-What is the correct way of returning an empty queryset in a Django View?
- [Django]-Django set DateTimeField to database server's current time
- [Django]-Is there a function for generating settings.SECRET_KEY in django?
Source:stackexchange.com