【问题标题】:Django ORM group by one column and return otherDjango ORM 按一列分组并返回其他
【发布时间】:2016-10-02 16:01:57
【问题描述】:

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

与此类似:

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。我想将结果作为结果对象,如

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

有人可以帮忙吗?

【问题讨论】:

    标签: python django orm


    【解决方案1】:

    values() 呼叫将您的QuerySet 进入dicts 的列表。

    如果您想保留QuerySet,但只从数据库中检索您感兴趣的字段,请使用only(*fields)defer(*fields)

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

    如果您尝试访问在实例上延迟的字段,则会导致额外的数据库命中。您可以验证这些是不完整的Results 实例:

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

    【讨论】:

      猜你喜欢
      • 2023-03-13
      • 2016-09-25
      • 1970-01-01
      • 2012-07-01
      • 2017-03-30
      • 1970-01-01
      • 2012-04-26
      • 2018-03-10
      • 1970-01-01
      相关资源
      最近更新 更多