Django ORM:Group by和Max

编程入门 行业动态 更新时间:2024-10-27 14:28:03
本文介绍了Django ORM:Group by和Max的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个如下所示的模型:

请求:user,req_time,req_text id,user_id,req_time,req_text 1 1 TIMESTAMP YES 2 1 TIMESTAMP NO 3 2 TIMESTAMP YES / pre>

等。

如何编写一个Django ORM查询:按用户分组请求,基于req_text过滤请求,还可以选择最终结果集的最大值。所以对于每个用户,我将返回一行与过滤条件匹配,并且也有最大的id。

解决方案

from django.db.models.aggregates import Max request_values = Requests.objects.filter(req_text ='YES')\ .values('user')\ .annotate(max_id = Max('id'))

I have a model that looks like this:

Requests: user, req_time, req_text

In the DB, the records can look like this:

id, user_id, req_time, req_text 1 1 TIMESTAMP YES 2 1 TIMESTAMP NO 3 2 TIMESTAMP YES

etc.

How do I write a Django ORM query that: groups the Requests by user, filters the Requests based on req_text, and also, select the max id of the resulting result set. So for each user, I will return one row which matches the filter condition and also has the greatest id.

解决方案

from django.db.models.aggregates import Max request_values = Requests.objects.filter(req_text='YES') \ .values('user') \ .annotate(max_id=Max('id'))

更多推荐

Django ORM:Group by和Max

本文发布于:2023-10-20 01:05:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1509371.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:ORM   Django   Max   Group

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!