我可以对查询集返回对象进行排序以发挥结果的作用 [英] Can i sort query set return objects in order to function result

查看:66
本文介绍了我可以对查询集返回对象进行排序以发挥结果的作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个基于Web的音乐应用程序,并且我想实现一些功能,以便用户在上周,本月,上个月能看到最喜欢的专辑。
,所以这是我的模型:

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??

推荐答案

order_by 方法转换为SQL ORDER BY ,因此仅适用于模型字段,对应于表格列。如果您打算按模型的方法对元素进行排序,则该方法将无效。
所以,如果您想完成类似的事情

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')

您必须使用python方式

You'll have to do it the python way

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

在性能方面,这意味着您将通过查询获取元素,然后使用python对其进行排序(这与一次性获取排序的查询集不同) 。
否则,如果您可以将 get_weekly_count 转换为原始SQL,则可以将其与 Count() extra 修饰符,将使 order_by 可用,即:

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')

看看 https://docs.djangoproject.com/ zh / 1.8 / ref / models / querysets /#extra

这篇关于我可以对查询集返回对象进行排序以发挥结果的作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆