2014-10-21 220 views
0

我有一個包含VM分析數據的表,每次輸入數據時都會插入一個時間戳。數據每小時輸入一次,並在30天標記處截斷。我需要編寫一個Django查詢來根據客戶發佈的整數來搜索給定的天數。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 

回答

2

你的基本查詢是差不多吧。只需在您的filter呼叫中使用datetime__gte=datetime.datetime.today() -datetime.timedelta(days=number_of_days)而不是datetime=...。正如所寫的,您要求的數據是在指定的天數前完成的,而不是從該天數到現在的數據。