【问题标题】:Django Date Range QueryDjango 日期范围查询
【发布时间】:2014-12-17 07:06:45
【问题描述】:

我有一个保存 VM 分析数据的表,每次输入数据时都会插入一个时间戳。数据每小时输入一次,并在 30 天标记处截断。我需要编写一个 Django 查询来根据客户发布的整数搜索给定的天数。

因此,客户提交数字 7,Django 查询返回最近 7 天的数据。我正在查看有关日期的文档,但它似乎不会做我想要的。

我真的只是需要一些帮助,关于在哪里寻找,或者是否可以使用 Django。

这是我当前的查询:

vms = VmStatHistories.objects.filter(customer_id = customer_id).order_by('vm_id').distinct('vm_id').filter(datetime =  datetime.datetime.today()-datetime.timedelta(days=number_of_days))

模型字段:

class VmStatHistories(models.Model):
    vm_stat_id = models.AutoField(primary_key=True, editable=False)
    vm_id = models.BigIntegerField()
    customer = models.ForeignKey(Customers)
    vm_name = models.CharField(max_length=4000)
    read_request = models.DecimalField(max_digits=15, decimal_places=2)
    write_request = models.DecimalField(max_digits=15, decimal_places=2)
    cpu_usage_ghz = models.DecimalField(max_digits=15, decimal_places=2)
    memory_consumed_mb = models.DecimalField(max_digits=15, decimal_places=2)
    memory_active_mb = models.DecimalField(max_digits=15, decimal_places=2)
    memory_swap_mb = models.DecimalField(max_digits=15, decimal_places=2)
    bytes_sent_kbps = models.DecimalField(max_digits=15, decimal_places=2)
    bytes_received_kbps = models.DecimalField(max_digits=15, decimal_places=2)
    disk_usage_mbps = models.DecimalField(max_digits=15, decimal_places=2)
    ip_address = models.CharField(max_length=16)
    provisioned_ram_gb = models.BigIntegerField()
    provisioned_cores = models.BigIntegerField()
    provisioned_storage_gb = models.BigIntegerField()
    consumed_storage_gb = models.BigIntegerField()
    datetime = models.DateTimeField()

    class Meta:
        managed = True
        db_table = 'vm_stat_histories'

    def __unicode__(self):  # Python 3: def __str__(self):
      return self.vm_name   

【问题讨论】:

    标签: python django postgresql django-views


    【解决方案1】:

    您的基本查询几乎是正确的。只需在您的filter 调用中使用datetime__gte=datetime.datetime.today() -datetime.timedelta(days=number_of_days) 而不是datetime=...。正如所写,您要求的是在指定天数前加上时间戳的数据,而不是从该天数到现在的数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-19
      • 2019-08-16
      • 2014-01-07
      • 2011-01-01
      相关资源
      最近更新 更多