如何在 Django 中编写此查询

How to write this query in Django

我有以下 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))

这是行不通的。任何帮助请

您似乎需要按服务器对数据进行过滤后分组。 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'))

More about aggregation.

一些注意事项:

  • django 和 sql 查询不同(在 sql 中你使用 great/less 然后,但在 django - great/less 或等于 然后)
  • 在你的情况下最好使用 rangetimestamp__range=(from_time, to_time)