我试图计算每周玩家玩的次数:
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,有没有一种好方法呢?
答案 0 :(得分:15)
您可以使用自定义聚合函数来生成查询:
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,因此最好使用raw query。
答案 1 :(得分:4)
以下是问题的示例和不理想的解决方法。以这个示例模型为例:
class Rating(models.Model):
RATING_CHOICES = (
(1, '1'),
(2, '2'),
(3, '3'),
(4, '4'),
(5, '5'),
)
rating = models.PositiveIntegerField(choices=RATING_CHOICES)
rater = models.ForeignKey('User', related_name='ratings_given')
ratee = models.ForeignKey('User', related_name='ratings_received')
此示例聚合查询失败的方式与您的相同,因为它尝试引用使用.extra()
创建的非字段值。
User.ratings_received.extra(
select={'percent_positive': 'ratings > 3'}
).aggregate(count=Avg('positive'))
一种解决方法
可以通过在额外值的定义中使用聚合数据库函数(在本例中为Avg)直接找到所需的值:
User.ratings.extra(
select={'percent_positive': 'AVG(rating >= 3)'}
)
此查询将生成以下SQL查询:
SELECT (AVG(rating >= 3)) AS `percent_positive`,
`ratings_rating`.`id`,
`ratings_rating`.`rating`,
`ratings_rating`.`rater_id`,
`ratings_rating`.`ratee_id`
FROM `ratings_rating`
WHERE `ratings_rating`.`ratee_id` = 1
尽管此查询中有不需要的列,但我们仍然可以通过隔离percent_positive
值来获取所需的值:
User.ratings.extra(
select={'percent_positive': 'AVG(rating >= 3)'}
).values('percent_positive')[0]['percent_positive']