Django注释()两步关系混淆

时间:2022-06-11 16:35:10

I have the following 3 models:

我有以下三个模型:

Category:
  date_start
  date_end
  active: bool

Player:
  name: str
  age: int
  category = models.ForeignKey(Category)

PlayerContact:
  contact_result: int
  player = models.ForeignKey(Player)

In this case I have:

在这种情况下,我有:

  • 2 Categories
  • 两类
  • 10 Players per Category
  • 每个类别10玩家
  • 1 to 3 Players in each Category with a contact_result = 3
  • 每个类别中有1到3个玩家,contact_result = 3

How do I annotate a Category queryset to get the amount of players with a contact_result=3?

如何注释一个Category queryset以获得contact_result=3的玩家数量?

I've tried this:

我已经试过这个:

Categories.objects.annotate(
    Count(
        'player', 
        filter=Q(player__playercontact__contact_result=3)
    )
) # returns all players for each Category

Categories.objects.annotate(
    Count('player__playercontact__contact_result')
) # returns players with a contact_result but it's not filtered

Something similar to this:

类似这样:

<CategoryQuerySet [<Category: Category object>, <Category: Category object>]>

# where each Category object is annotated by the count() of Players with,
# a PlayerContact's contact_result = 3

2 个解决方案

#1


1  

instead of annotate, try count chained to the filter

不要注释,尝试连接到过滤器的count

Categories.objects.filter(Q(player__playercontact__contact_result=3)).count()

#2


0  

I ended up doing this:

最后我这样做了:

cats_and_numbers = [(cat, PlayerContact.objects.filter(contact_result=3,
                    player__category_id=cat.id).count()) for cat in queryset]

won't mark this as correct tho since I'm quite sure there is a proper way to do it.

我不认为这是正确的,因为我很确定有一个合适的方法。

Edit:

编辑:

If this was actually the best way to do it, I'd probably create a manager to reduce visual noise, something like: PlayerContact.objects.denied() # denied is just a random word, to illustrate.

如果这实际上是最好的方法,我可能会创建一个管理器来减少视觉噪音,比如:playercontact.objects.deny () # denied只是一个随机的单词,以说明这一点。

#1


1  

instead of annotate, try count chained to the filter

不要注释,尝试连接到过滤器的count

Categories.objects.filter(Q(player__playercontact__contact_result=3)).count()

#2


0  

I ended up doing this:

最后我这样做了:

cats_and_numbers = [(cat, PlayerContact.objects.filter(contact_result=3,
                    player__category_id=cat.id).count()) for cat in queryset]

won't mark this as correct tho since I'm quite sure there is a proper way to do it.

我不认为这是正确的,因为我很确定有一个合适的方法。

Edit:

编辑:

If this was actually the best way to do it, I'd probably create a manager to reduce visual noise, something like: PlayerContact.objects.denied() # denied is just a random word, to illustrate.

如果这实际上是最好的方法,我可能会创建一个管理器来减少视觉噪音,比如:playercontact.objects.deny () # denied只是一个随机的单词,以说明这一点。