Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am writing a web based music application and I want implement some feature that user can see most favor album in last week-month-year. so this is my model :

class album(models.Model):
   def get_weely_count():
      ...
   def get_monthly_count():
      ...

   def get_yearly_count():
      ...

class like(models.Model):
   created_at = models.DateField()
   albumID = models.ForeignKey(Album)

Now I want to receive albums that most liked in last week or last month or last year,I want done some thing like this(but I can not):

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

can any one help me to fix it or give another approach to achieve that goal??

like image 882
alireza sadeghpour Avatar asked Jan 07 '23 18:01

alireza sadeghpour


1 Answers

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

like image 119
Alessio Moretti Avatar answered Jan 16 '23 09:01

Alessio Moretti