Follow up: Count of Group Elements With Joins in Django

为君一笑 提交于 2019-12-11 07:57:25

问题


In order to build on this question here, we encountered another problem regarding aggregate annotations in the Django ORM.

Because we need a join within our query it leads to this clumsy "extra" statement:

Entry.objects.all()
             .extra(select={'week_year': "TO_CHAR(entry_addition.date, 'IW/YYYY')"}, where=["addition_id=entry_addition.id"], tables=['entry_addition'])
             .values('week_year')
             .annotate(Count('addition'))

We created those the following two classes to get rid of the "extra" statement.

class ToChar(Aggregate):
    name = 'ToChar_pg'

    WEEK_YEAR = 'IW/YYYY'

    def __init__(self, lookup, format_, **extra):
        extra['format_'] = format_
        super(ToChar, self).__init__(lookup, **extra)
django.db.models.ToChar = ToChar


class ToChar_pg(django.db.models.sql.aggregates.Aggregate):

    sql_function = 'TO_CHAR'
    sql_template = """%(function)s(%(field)s, '%(format)s')"""

    def __init__(self, col, format_=None, source=None, distinct=False, **extra):
        extra['format'] = format_
        super(ToChar_pg, self).__init__(col, source=source, distinct=distinct, **extra)
django.db.models.ToChar_pg = ToChar_pg

So now, we got this ORM expression:

Entry.objects.all()
             .annotate(week_year=ToChar('addition__date', ToChar.WEEK_YEAR))
             .values('week_year')
             .annotate(count=Count('addition'))

That is the desired SQL statement:

SELECT TO_CHAR("entry_addition"."date", 'IW/YYYY') AS "week_year", COUNT("entry"."addition_id") AS "count"
FROM "entry" LEFT OUTER JOIN "entry_addition" ON ("entry"."addition_id" = "entry_addition"."id")
GROUP BY week_year

That is the actual output:

SELECT TO_CHAR("entry_addition"."date", 'IW/YYYY') AS "week_year", COUNT("entry"."addition_id") AS "count"
FROM "entry" LEFT OUTER JOIN "entry_addition" ON ("entry"."addition_id" = "entry_addition"."id")

Now, the following question arises: where is the "GROUP BY" clause?

来源:https://stackoverflow.com/questions/25081183/follow-up-count-of-group-elements-with-joins-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!