2010-08-30 48 views
3

有沒有人有一個簡單的解決方案來使用(或修改)dumpdata來將一個簡單的表截斷到最後n行。我喜歡爲測試裝置使用轉儲數據,但數據大小變得如此之大,這沒有任何意義。順便說一句 - 我沒有設計表格,我只是需要處理它的吸盤。Django - dumpdata截斷爲最後n行

對於那些可能會問這裏的結構如何看起來是這樣的。

從側面的Django

class GridResourceUsage(models.Model): 
    """Sampled point in time of license usage for individual grid resource. Includes who and quanity.""" 
    timestamp = models.DateTimeField(db_index=True) 
    grid_license_resource = models.ForeignKey(GridLicResource) 
    total = models.IntegerField(default=None, null=True) 
    limit = models.IntegerField(default=None, null=True) 
    free  = models.IntegerField(default=None, null=True) 
    intern = models.IntegerField(default=None, null=True) 
    extern = models.IntegerField(default=None, null=True) 
    waiting = models.IntegerField(default=None, null=True) 
    def __unicode__(self): 
     return str("GRU-" + self.grid_license_resource.name) 
    class Meta: 
     ordering = ['-timestamp'] 
    @models.permalink 
    def get_absolute_url(self): 
     return('hist_res_id',(), {'resource': str(self.grid_license_resource.name), 'id':str(self.id)}) 

從MySQL側

CREATE TABLE `gridresource_gridresourceusage` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `timestamp` datetime NOT NULL, 
    `grid_license_resource_id` int(11) NOT NULL, 
    `total` int(11) DEFAULT NULL, 
    `limit` int(11) DEFAULT NULL, 
    `free` int(11) DEFAULT NULL, 
    `intern` int(11) DEFAULT NULL, 
    `extern` int(11) DEFAULT NULL, 
    `waiting` int(11) DEFAULT NULL, 
    PRIMARY KEY (`id`), 
    KEY `gridresource_gridresourceusage_timestamp` (`timestamp`), 
    KEY `gridresource_gridresourceusage_grid_license_resource_id` (`grid_license_resource_id`) 
) ENGINE=MyISAM AUTO_INCREMENT=2891167 DEFAULT CHARSET=latin1; 

回答

4

我不知道如果dumpdata可以做你要求什麼。

難道你不能只是創建一個查詢集和serialize嗎?有點愚蠢的例子,但它應該工作。

# Create queryset you want 
n = SomeModel.objects.count()-1 # Row offset counting from the end 
queryset = SomeModel.objects.all()[n:] 

# Serialize that queryset to json in this case 
from django.core import serializers 
data = serializers.serialize("json", queryset) 

# And write it into the file 
f = open('data.json', 'w') 
f.write(data) 
f.close() 

可以在management command這個包裹起來,並用它或多或少正在使用的dumpdata命令以同樣的方式。 (你也可以看看dumpdata的想法來源)