【问题标题】:Using .annotate() and extra() together in django在 django 中一起使用 .annotate() 和 extra()
【发布时间】:2010-06-01 17:43:06
【问题描述】:

在制作查询集时,我似乎不能同时使用 annotate 和 extra 这个

discussions = game.gamediscussion_set.filter(reply_to=None).annotate(up_votes = Count('userUpVotes'), down_votes=Count('userDownVotes')).extra(select={'votes':"'userUpVotes' - 'userDownVotes'"}).order_by('votes')

返回

Caught Warning while rendering: Truncated incorrect DOUBLE value: 'userUpVotes'

我想同时添加 userUpVotes 和 userDownVotes 以获得“投票”字段,然后按此字段排序。

userUpVotes 是用户的相关 ManyToManyField(与 userDownVotes 一样)。所以我需要先数这些。

有什么想法吗?

【问题讨论】:

  • 如果你把单个的引号去掉,它会起作用吗?例如'votes': "userUpVotes - userDownVotes"
  • 更新了我的问题,也做了修改。删除反逗号并没有什么不同,但是我有一个从我的新查询中引发的新错误。这是“(1054,“'字段列表'中的未知列'up_votes'”)”

标签: django annotate extra


【解决方案1】:

如果您将投票存储在同一个表或列中,这种事情会容易得多,+1 表示赞成票,-1 表示反对票。您仍然可以通过简单的过滤器轻松计算赞成或反对票的数量,通过简单的计数计算总票数,并通过总和计算总分。

在单独的表格中存储投票的示例代码。

CHOICES = {
    1: 'UP',
    -1: 'DOWN'
}

class Vote(models.Model):
    user = models.ForiegnKey(User) # prevent ballot stuffing
    game = models.ForiegnKey(Game)
    vote = models.IntegerField(choices=CHOICES)

total_up_votes = Vote.objects.filter(game=GAME_INSTANCE).filter(vote=1).count()
total_votes = Vote.objects.filter(game=GAME_INSTANCE).count()
total_score = Vote.objects.filter(game=GAME_INSTANCE).aggregate(total=Sum('vote'))

total_score 将是一个字典:{'total': }

【讨论】:

    猜你喜欢
    • 2011-06-21
    • 1970-01-01
    • 1970-01-01
    • 2012-10-02
    • 1970-01-01
    • 2014-10-12
    • 2011-07-08
    • 2013-10-19
    • 2015-10-06
    相关资源
    最近更新 更多