一尘不染

在Django查询中使用.extra(select = {…})引入的值上使用.aggregate()?

django

我正在尝试这样计算一个球员每周玩的次数:

player.game_objects.extra(
    select={'week': 'WEEK(`games_game`.`date`)'}
).aggregate(count=Count('week'))

但是Django抱怨

FieldError: Cannot resolve keyword 'week' into field. Choices are: <lists model fields>

我可以这样在原始SQL中完成

SELECT WEEK(date) as week, COUNT(WEEK(date)) as count FROM games_game
WHERE player_id = 3
GROUP BY week

有没有在Django中不执行原始SQL的好方法?


阅读 813

收藏
2020-03-30

共1个答案

一尘不染

你可以使用自定义聚合函数来生成查询:

WEEK_FUNC = 'STRFTIME("%%%%W", %s)' # use 'WEEK(%s)' for mysql

class WeekCountAggregate(models.sql.aggregates.Aggregate):
    is_ordinal = True
    sql_function = 'WEEK' # unused
    sql_template = "COUNT(%s)" % (WEEK_FUNC.replace('%%', '%%%%') % '%(field)s')

class WeekCount(models.aggregates.Aggregate):
    name = 'Week'
    def add_to_query(self, query, alias, col, source, is_summary):
        query.aggregates[alias] = WeekCountAggregate(col, source=source, 
            is_summary=is_summary, **self.extra)


>>> game_objects.extra(select={'week': WEEK_FUNC % '"games_game"."date"'}).values('week').annotate(count=WeekCount('pk'))
2020-03-30