我有一个简单的表,其中包含以下值
"uid": "some_uid",
"name": "test1",
"trig_time": 1234, #unix timestamp
"notify_time": 1235 #unix timestamp
我有很多元组可能有相同的名称,也可能没有相同的名称。我打算根据名称对结果进行分组,并将计数数和最新触发时间作为结果返回。例如,对于以下元组
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')
根据评论, 我使用的是djangorest框架,下面是我的模型
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')
我是否也必须更改序列化程序代码?我在djangoshell中执行了查询,结果很好。但是在服务器中,我得到以下错误
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 ^{} 到达:
(请参阅文档以了解为什么需要最后一个空的
order_by()
)。你知道吗这将为您提供每个
name
项的计数,以及每组最新的trig_time
。你知道吗相关问题 更多 >
编程相关推荐