gpt4 book ai didi

django - 如何根据对外部字段的引用计数获取查询集

转载 作者:行者123 更新时间:2023-12-04 01:18:57 25 4
gpt4 key购买 nike

关于如何执行 django 查询的问题。
我有一个游戏模型
使用“通过”ManyToManyField
到用户模型。

class Game(models.Model):
# other misc game-description fields...
players = models.ManyToManyField(User, through='PlayerGameResult',
blank=True, null=True)

class PlayerGameResult(models.Model):
game = models.ForeignKey(Game)
player = models.ForeignKey(User)
dtime_played = models.DateTimeField(default=datetime.now)
# ...

如果 1 个以上的玩家玩过特定游戏,
那么游戏模型中的玩家字段将有
1+ 引用。否则玩家为空。查询问题请引用??????以下....
# all games not yet played by this user...
games_qset = Game.objects.exclude(players__username=request.user.username)

# out of all the games not played by this user, extract the ones not
# yet played by anyone else either (this user would be the 1st player)
games_unplayed_qset = games_qset.filter(players__isnull=True)


# here's the question: out of all the games that have not been played by
# this user, get a queryset that extracts only the games that have been
# played by more than 10 (GAME_WITH_FEW_PLAYERS_THRESHOLD) players
# ?????? this is the query I don't know how to make... ?????
#
# in the following example, I want to get back a queryset that includes only
# Game Ids 6 and 19, because they have players count 20 and 12 (> threshold 10)
#
# (Pdb) for rec in games_qset: print rec
# Game id 6, Num players: 20
# Game id 7, Num players: 5
# Game id 13, Num players: 0
# Game id 19, Num players: 12
#
# for a count of all games that have been played by at least one player:
# (Pdb) games_qset.filter(players__isnull=False).count()
# 3
#

有任何想法吗?谢谢你。
胡安

最佳答案

当您在排除中说“提取”时会令人困惑。

答案在于注释和聚合。
http://docs.djangoproject.com/en/dev/topics/db/aggregation/

from django.db.models import Count
Games.objects.annotate(num_players=Count('players')).filter(num_players__gt=10)

关于django - 如何根据对外部字段的引用计数获取查询集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5080366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com