Django ORM按一列分组并返回另一列 [英] Django ORM group by one column and return other

查看:329
本文介绍了Django ORM按一列分组并返回另一列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在简单的世界中,我尝试在Django中编写一个查询,该查询将返回结果

In simple worlds I try to write in Django a query which will return results

与此类似:

select id, max(score), screen, details from results
group by screen
where user_id=123
order by score desc, screen

我的代码:

results = Results.objects.filter(user=user).values('screen').annotate(score=Max('score')).order_by('-score', 'screen')

但是我没有返回结果对象,而是json.我想获得结果作为

But i doesn't return Results objects but json. I would like to get results as Results object like

user = User.objects.filter(id=id)
results = Results.objects.filter(user=user).order_by('-score', 'screen')

任何人都可以帮忙吗?

推荐答案

它是如果要将其保留为QuerySet,但仅从感兴趣的数据库中检索字段,请使用

If you want to keep it a QuerySet, but only retrieve the fields from the database that you are interested in, use only(*fields) or defer(*fields)

results = Results.objects.filter(user=user)
                         .annotate(score=Max('score'))
                         .order_by('-score', 'screen')
                         .only('screen')  # not values()

如果尝试访问实例上延迟的字段,将导致额外的数据库命中.您可以验证以下是否是不完整的Results实例:

If you try to access fields that were deferred on instances it will result in extra db hits. You can verify that these are incomplete Results instances:

> type(results[0])
<class 'app_name.Results_Deferred_foo_bar_7265632c0017c141e84a00d9fdb4760'>

这篇关于Django ORM按一列分组并返回另一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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