Du kan bruge en tilpasset aggregeret funktion til at producere din forespørgsel:
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'))
Men da denne API er udokumenteret og allerede kræver bits af rå SQL, er du måske bedre stillet ved at bruge en rå forespørgsel .