我有以下SQL查询。
SELECT server, count(server)
FROM host
WHERE host_id = 528
AND server != '' AND server IS NOT NULL
AND timestamp > '2015-03-08' AND timestamp < '2015-03-10'
GROUP BY server;
我尝试将其写为
query = (models.Host.objects
.values_list(server).filter(host_id=host.id,
timestamp__gte=datetime.datetime.strptime(from_time,'%Y-%m-%d'),
timestamp__lte=datetime.datetime.strptime(to_time, ''%Y-%m-%d'),
server__isnull=False))
这不起作用。请帮忙
答案 0 :(得分:0)
在过滤后看起来需要按服务器分组数据。 Django具有聚合功能,可以满足您的需求:
from django.db.models import Count
query = models.Host.objects.filter(
host_id=host.id,
timestamp__gt=datetime.datetime.strptime(from_time,'%Y-%m-%d'),
timestamp__lt=datetime.datetime.strptime(to_time, '%Y-%m-%d'),
server__isnull=False).values('server').annotate(server_count=Count('server'))
一些注意事项:
timestamp__range=(from_time, to_time)