Can i sort query set return objects in order to function result

核能气质少年 提交于 2019-12-05 19:43:19

The order_by method translates into an SQL ORDER BY, therefore it works only with model fields, which correspond to table columns. It won't work if you intend to sort your elements by a model's method. So, if you want to accomplish something like

Album.objects.all().order_by('get_weekly_count')

You'll have to do it the python way

sorted(Album.objects.all(), key=lambda x: x.get_weekly_count())

Performance-wise, this means you'll get your elements with a query and then you'll sort them with python (that's different from getting a sorted queryset in one shot). Otherwise, if it's possible for you to turn get_weekly_count into raw SQL, you could use it with a Count() or an extra modifier, that would make order_by usable, i.e.:

Album.objects.all().extra(
    select={'weekly_count': "<some SQL>"},
    select_params=(<you params>,),
).order_by('weekly_count')

Have a look at https://docs.djangoproject.com/en/1.8/ref/models/querysets/#extra

According to the documentation, you should use:

from django.db.models import Count
like.objects.filter(created_at__gt=START_OF_MONTH, created_at__lt=Datetime.now()).values('albumID').annotate(count=Count('albumID')).order_by('count')

This will get results for you in single db query. For more details visit https://docs.djangoproject.com/en/dev/topics/db/aggregation/.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!