简体   繁体   English

在 Django 中,如何根据子查询的子查询获取记录数?

[英]In Django, how can I get a count of records based on a subquery of a subquery?

A baseball player plays in a game if he makes one or more appearances in that game.如果棒球运动员在该比赛中出场一次或多次,则他将参加比赛。 So, to get a count of the number of games a player played in, you need to count the games that have an inning that have an appearance by that player.因此,要计算一名球员参加的比赛数量,您需要计算该球员出场的局数。

Here are my models:这是我的模型:

class Player(models.Model):
    ...

class Game(models.Model):
    ...

class Inning(models.Model):
    game = models.ForeignKey(Game, on_delete=models.CASCADE)

class Appearance(models.Model):
    inning = models.ForeignKey(Inning, on_delete=models.CASCADE)
    player = models.ForeignKey(Player, on_delete=models.CASCADE)

The SQL query to achieve what I want is:实现我想要的 SQL 查询是:

SELECT COUNT(*)
FROM games_game
WHERE id IN (SELECT game_id
             FROM innings_inning
             WHERE id IN (SELECT inning_id
                          FROM appearances_appearance
                          WHERE player_id = 1)) 

How could I do this in Django without using Raw SQL?我怎么能在不使用原始 SQL 的情况下在 Django 中做到这一点?

Note that this is for a PlayerDetailView , so I just need it for a single Player object.请注意,这是针对PlayerDetailView ,所以我只需要它用于单个Player对象。

You can perform such count with:您可以使用以下方法执行此类计数:

Game.objects.filter(inning__appearance__player=my_player).distinct().count()

Where my_player is the player where you want to count the Game s for.其中my_player是您要为其计算Game的玩家。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM