按一个ForeignKey字段的顺序排序? [英] Order by count of a ForeignKey field?

查看:93
本文介绍了按一个ForeignKey字段的顺序排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这几乎肯定是一个重复的问题,在这种情况下,道歉,但是我一直在搜索大约半个小时,在这里找不到答案。我可能使用错误的搜索字词,抱歉。

This is almost certainly a duplicate question, in which case apologies, but I've been searching for around half an hour on SO and can't find the answer here. I'm probably using the wrong search terms, sorry.

我有一个用户模型和一个提交模型。每个提交内容都有一个名为user_submitted的ForeignKey字段,用于上传它的用户。

I have a User model and a Submission model. Each Submission has a ForeignKey field called user_submitted for the User who uploaded it.

class Submission(models.Model):
    uploaded_by = models.ForeignKey('User')
class User(models.Model):
    name = models.CharField(max_length=250 )

我的问题很简单:如何获取最多提交的三位用户的列表?

My question is pretty simple: how can I get a list of the three users with the most Submissions?

我尝试在用户模型上创建一个num_submissions方法:

I tried creating a num_submissions method on the User model:

def num_submissions(self):
    num_submissions = Submission.objects.filter(uploaded_by=self).count()
    return num_submissions

然后执行:

top_users = User.objects.filter(problem_user=False).order_by('num_submissions')[:3]

但是,与我尝试的所有其他事情一样,这样做失败了。我可以使用智能数据库查询来实现吗?或者我应该在视图文件中做更多的事情?

But this fails, as do all the other things I've tried. Can I actually do it using a smart database query? Or should I just do something more hacky in the views file?

推荐答案

from django.db.models import Count
top_users = User.objects.filter(problem_user=False) \
                .annotate(num_submissions=Count('submission')) \
                .order_by('-num_submissions')[:3]

你没有提到 problem_user 在你的示例模型代码,但我已经离开它假设它是一个 BooleanField 用户

这篇关于按一个ForeignKey字段的顺序排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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