一尘不染

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

mysql

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

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的好方法?


阅读 250

收藏
2020-05-17

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

但是由于此API未公开,并且已经需要一些原始SQL,因此使用原始查询可能会更好。

2020-05-17