【问题标题】:Django - dumpdata truncate to last n linesDjango - 转储数据截断到最后 n 行
【发布时间】:2011-04-05 19:34:59
【问题描述】:

有没有人有一个简单的解决方案来使用(或修改)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;

【问题讨论】:

    标签: django django-models django-admin mysqldump


    【解决方案1】:

    我不确定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 的来源以获得想法)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-06
      • 1970-01-01
      • 2019-03-07
      • 1970-01-01
      相关资源
      最近更新 更多