Django过滤器按与ForeignKey相关的对象数进行排序 [英] Django filter sort by number of ForeignKey related objects

查看:59
本文介绍了Django过滤器按与ForeignKey相关的对象数进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网站,其中列出了徒步旅行的目录,用户可以记录他们已经进行了徒步旅行.我具有搜索功能,我希望能够按用户完成远足的次数对远足列表进行排序.我发现这篇文章看似相关,但它是指外键模型中的特定字段,而我只想计算实例总数: Django QuerySet按反向外键匹配数进行排序

I have a website which catalogs hikes, and users can log that they have gone on these hikes. I have a search function, and I want to be able to sort my list of hikes by the amount of times they have been completed by my users. I found this post which seems relevant, but is referring to a specific field in the foreignkey model, whereas I'd like to just count the total number of instances: Django QuerySet ordering by number of reverse ForeignKey matches

以下是一些示例代码:

models.py:

models.py:

class Hikes(models.Model)
...    

class UserLog(models.Model)
     user = models.ForeignKey(User, on_delete=CASCADE)
     hike = models.ForeignKey(Hikes, on_delete=CASCADE)

我需要从我的Hikes模型中生成一个查询集,该查询集计算UserLog引用每次加息的次数,然后从引用次数最多到最少的顺序进行排序.像这样:

I need to generate a queryset from my Hikes model that counts the number of times UserLog has referenced each hike, and then orders the hikes from most referenced to least. Something like this:

Hikes.objects.order_by(每次加息时,在UserLog中计算参考编号,然后按参考编号顺序排列)

Hikes.objects.order_by(for each hike, count # of references in UserLog, then place in order by # of references)

因此,如果Hike#1具有10个UserLog实例,Hike#2具有20个,而Hike#3具有5个,则QuerySet将返回:远足2,远足1,远足3

So if Hike #1 has 10 UserLog instances, Hike #2 has 20, and Hike #3 has 5, the QuerySet would return: Hike #2, Hike #1, Hike #3

有什么提示吗?

感谢viviwill,这是搜索字段中的工作代码:

thanks to viviwill, here is the working code in a search field:

def hike_list(request):
    qs = Hikes.objects.all()
    ...
    if request.GET:
        ...
        searchsort = request.GET.get('sortby', '')
        if searchsort == 'sortlocalrepeats':
            qs = qs.annotate(count=Count('userlog')).order_by('-count')

推荐答案

视图中:

context['rank_hike'] = Hikes.objects.annotate(number_of_hikes=Count('UserLog')).order_by('-number_of_hikes')

在模板中:

{% for hike in rank_hike %}
<p>{{ hike }} {{ hike.number_of_entries }}</p>
{% endfor %}

这篇关于Django过滤器按与ForeignKey相关的对象数进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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