python - 在 Django ORM 中执行 Groupby

标签 python django

我有一个包含以下值的简单表格

 "uid": "some_uid",
 "name": "test1",
 "trig_time": 1234, #unix timestamp
 "notify_time": 1235  #unix timestamp

我有很多元组,它们可能具有相同的名称,也可能不具有相同的名称。我打算根据名称对结果进行分组,并返回计数数量和最新的 trig_time 作为结果。例如,对于以下元组

name,trig_time,notify_time
test1,1234,1235
test1,1236,1237
test2,1238,1239

预期结果

name,count,latest_trig_time
test1,2,1236
test2,1,1238

我尝试了以下查询。我不确定我做错了什么。

queryset = Trig.objects.filter(uid=uid).annotate(count=Count('name')).order_by('name')

根据评论, 我正在使用 Djangorestframework 以下是我的模型

class Trig(models.Model):
    uid = models.CharField(max_length=100, blank=False)
    name = models.CharField(max_length=100, blank=False)
    trig_time = models.BigIntegerField(blank=False)
    notify_time = models.BigIntegerField(default=0)

    class Meta:
        unique_together = ('name', 'uid', 'trig_time')

我是否也必须更改我的序列化器代码?我在 django shell 中执行了查询,效果很好。但在服务器中,我收到以下错误

The serializer field might be named incorrectly and not match any attribute or key on the dict instance.

以下是我的序列化器代码

class TrigSerializer(serializers.ModelSerializer):
    class Meta:
        model = Trig
        fields = ('uid','name','trig_time','notify_time') 

最佳答案

您可以使用aggregation with values()到达那里:

from django.db.models import Count, Max

Trig.objects.filter(uid=uid).values('name')\
                    .annotate(count=Count('id'), latest_trig=Max(trig_time))\
                    .order_by()

(请参阅文档了解为什么需要最后一个空 order_by())。

这将为您提供每个 name 项目的计数,以及每个组的最新 trig_time

关于python - 在 Django ORM 中执行 Groupby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38517142/

相关文章:

python - 对于仅包含整数的文件,基数为 10 的 int() 的文字无效

python - 修复格式错误的字符串?

python - has_permission() 缺少 1 个必需的位置参数 : 'view'

python - 按下按钮后多次更改 tkinter 输入小部件

python - 如何使用 python 2.7 64 位在 virtualenv 中安装 pywin32?

python - Pylons Mako undefined variable

python - 每次调用 authenticate() 后用户密码都会改变

python - Fabric + django异步提示输入sudo密码

python - 使用 Django 获取 JSON 数据

python - django模型字段检查实例