在 django 中一起使用 .annotate() 和 extra()

发布于 2024-09-04 04:08:45 字数 547 浏览 4 评论 0原文

在制作查询集时,我似乎无法同时使用注释和额外功能 这

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 也是如此)。所以我需要先数一下这些。

有什么想法吗?

It seems i cannot use annotate and extra together when making a queryset
This

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

returns

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

I want to add both userUpVotes and userDownVotes together to get a 'votes' field, then order by this field.

userUpVotes is a related ManyToManyField of users (as is userDownVotes). So i need to count these first.

Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

焚却相思 2024-09-11 04:08:45

如果您将投票存储在同一个表或列中,则此类事情会容易得多,其中赞成票的值为 +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': }

This sort of thing is a lot easier if you store votes in the same table or column, with a value of +1 for an up vote and -1 for a down vote. You can still easily count the number of up or down votes with a simple filter, calculate the total number of votes with a simple count, and calculate the total score with the sum aggregate.

Sample code for storing votes in a separate table.

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 will be a dict: {'total': }

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文