【问题标题】:Django aggregate on .extra valuesDjango 聚合 .extra 值
【发布时间】:2012-10-22 08:21:42
【问题描述】:

模型,带有抽象基类:

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

现在,我想使用 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

这会给我一张表格,上面有每天和每小时的炸弹数量。

使用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'))

但 Django 抱怨 FieldError: Cannot resolve keyword 'date' into field。有没有办法使用 Django ORM 来获得所需的结果,还是我需要回退到原始 sql?

【问题讨论】:

    标签: django orm aggregate


    【解决方案1】:

    这行得通吗?

    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'))
    

    【讨论】:

    • 哇,好用,太棒了!尽管如此,从我收集的 Django 文档中,您需要将额外字段设置为 select = ... ,您还没有在这里完成吗?不知道这意味着什么......
    • 第一个参数是select,不管你有没有命名。
    • 这在 Django 1.5 中不起作用。是从那以后添加的吗? User.objects.extra({'started':'1'}).values('started').order_by('started').annotate(Count('started')) 给FieldError: Cannot resolve keyword 'started' into field.
    猜你喜欢
    • 2017-01-15
    • 1970-01-01
    • 2010-12-20
    • 2014-07-15
    • 2019-01-15
    • 2013-10-08
    • 2020-06-08
    • 2015-12-29
    • 2011-01-20
    相关资源
    最近更新 更多