Django聚合.extra值

pet*_*lux 1 django orm aggregate

模型,带抽象基类:

class MapObject(models.Model):
    start_date = models.DateTimeField(default= datetime.strptime('1940-09-01T00:00:00',  '%Y-%m-%dT%H:%M:%S'))
    end_date = models.DateTimeField(default= datetime.strptime('1941-07-01T00:00:00',  '%Y-%m-%dT%H:%M:%S'))
    description = models.TextField(blank=True)
    location = models.PointField()
    objects = models.GeoManager()
    user = models.ForeignKey(User)
    created = models.DateTimeField(auto_now_add = True)
    last_modified = models.DateTimeField(auto_now = True)
    source = models.ForeignKey(Source)
    address= models.TextField(blank=True, null=True)
    address_road = models.TextField(blank=True, null=True)

class Meta:
    abstract = True

class Bomb(MapObject, BombExtraManager):
    #Bomb Attributes
    type = models.CharField(choices= Type_CHOICES, max_length=10)
    night_bombing = models.BooleanField(blank=True)
    map_sheet = models.ForeignKey(MapSheet, blank=True, null=True)
    def __unicode__(self):
        return self.type
Run Code Online (Sandbox Code Playgroud)

现在,我希望使用Django ORM获得与此查询相同的结果:

Select date_part('day',"start_date") as "day", date_part('hour',"start_date") as "hour", Count('id')
from "Mapper_bomb"
where "source_id" = 1
group by date_part('hour',"start_date"), date_part('day',"start_date")
Order by date_part('day',"start_date") ASC, date_part('hour',"start_date") ASC
Run Code Online (Sandbox Code Playgroud)

哪个会给我一张每天和每小时炸弹数量的表格.

使用Django ORM,我现在得到了以下内容(first_day只是我定义的一个自定义管理器,返回数据的子集,与source_id = 1相同):

Bomb.first_day.extra(select={'date': "date_part(\'day\', \"start_date\")", 'hour': "date_part(\'hour\', \"start_date\")"}).values('date', 'hour').order_by().annotate(Count('date'), Count('hour'))
Run Code Online (Sandbox Code Playgroud)

但Django抱怨FieldError:无法将关键字'date'解析为字段.有没有办法使用Django ORM来获得所需的结果,还是我需要回退原始的sql?

Pav*_*sov 7

这有用吗?

Bomb.first_day.extra({
        'date': "date_part(\'day\', \"start_date\")",
        'hour': "date_part(\'hour\', \"start_date\")"
    }).values('date', 'hour').order_by('date', 'hour').annotate(Count('id'))
Run Code Online (Sandbox Code Playgroud)

  • 这在Django 1.5中不起作用.它是否被添加?`User.objects.extra({'started':'1'}).values('started').order_by('started').annotate(Count('started'))`给出`FieldError:无法解析关键字'开始'进入田野 (3认同)