Django注释总和的平均值(1.6.5)

时间:2015-10-29 21:42:27

标签: python mysql django django-queryset django-1.6

目前正试图获取一个组的平均值,但当我尝试执行正确的查询集时,它会抱怨语法不正确

objs = MyModel.objects.filter(...).values('user', 'value')
objs = objs.annotate(sum=Sum('value')) 
# i've also tried adding `.values('sum')` to the above
objs = objs.aggregate(Avg('sum')) # whines here

有没有办法在没有放入SQL的情况下执行此操作?所需的SQL沿着

SELECT AVG(`sum`) as `avg` FROM ( 
    SELECT SUM(`appname_mymodel`.`value`) AS `sum`
    FROM `appname_mymodel` 
    GROUP BY 
        `appname_mymodel`.`user_id`, `appname_mymodel`.`value`
) as subquery ORDER BY NULL;

不确定django是否能很好地使用子查询。

以下是错误消息:

ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM (SELECT SUM(`appname_mymodel`.`value`) AS `sum` FROM `appname_' at line 1")

Django版 - 1.6.5

MySQL版本 - 5.5

注意:

  • 如果我放弃values(分组依据),它可以正常工作(即objs.filter(...).annotate(...).aggregate(...)
  • 以下示例足以作为完全可重复的示例。

型号:

# Create your models here.

class UserProfile(models.Model):
    name = models.CharField(max_length=200)

class OtherFK(models.Model):
    name = models.CharField(max_length=200)

class MyModel(models.Model):
    # Happens if value is CharField or IntegerField
    value = models.CharField(max_length=200, blank=True, null=True)
    date = models.DateField()
    user = models.ForeignKey(UserProfile)
    other_fk = models.ForeignKey(OtherFK)

示例:

>>> from app_name.models import UserProfile, OtherFK, MyModel
>>> up = UserProfile.objects.create(name="test")
>>> fk = OtherFK.objects.create(name="test")
>>> v1 = MyModel.objects.create(user=up, other_fk=fk, value="12", date="2015-10-01")
>>> v2 = MyModel.objects.create(user=up, other_fk=fk, value="13", date="2015-10-02")
>>> from django.db.models import Sum,Avg
>>> MyModel.objects.all().values("user").distinct().annotate(sum=Sum("value")).aggregate(Avg('sum'))
ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM (SELECT DISTINCT `app_name_mymodel`.`user_id` AS `user_id`, SUM(`app_name_m' at line 1")
>>> MyModel.objects.all().values("user").distinct().annotate(sum=Sum("value"))
[{'sum': 25.0, 'user': 1L}]
>>> print MyModel.objects.all().values("user").distinct().annotate(sum=Sum("value")).query
SELECT DISTINCT `app_name_mymodel`.`user_id`, SUM(`app_name_mymodel`.`value`) AS `sum` FROM `app_name_mymodel` GROUP BY `app_name_mymodel`.`user_id` ORDER BY NULL

2 个答案:

答案 0 :(得分:0)

我认为这就是您所需要的,请在测试下面的一行后给出反馈:

MyModel.objects.filter(...).values('user__id').distinct().annotate(sum=Sum('value')).aggregate(Avg('sum'))

答案 1 :(得分:0)

看起来这是Django 1.6中的known bug,需要升级到1.7+才能修复

现在,我将在python中进行数学运算。