为了巩固这个问题在这里,我们遇到关于Django的ORM总计注解另一个问题。
因为我们需要我们的查询中的加入它导致了这种笨拙的“额外”的声明:
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'))
我们创建的那些以下两类摆脱了“额外”的说法。
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
所以,现在,我们得到这个ORM表达式:
Entry.objects.all()
.annotate(week_year=ToChar('addition__date', ToChar.WEEK_YEAR))
.values('week_year')
.annotate(count=Count('addition'))
这是所需的SQL语句:
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
这是实际的输出:
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”子句?