gpt4 book ai didi

python - 在 Django ORM 中执行 Groupby

转载 作者:太空宇宙 更新时间:2023-11-03 16:20:34 27 4
gpt4 key购买 nike

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

 "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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com