问题是
match
是
不
一
Match
对象,它是
QuerySet
包含零个、一个或多个
匹配
物体。因此您不能使用
hot_league
在这种情况下的关系
槲寄生
.
如果你想数一数
HotLeague
属于
request.user
,然后
匹配
属于那个
请求.用户
同样,您可以将其计算为:
HotLeague.objects.filter(user=request.user, match__user=request.user).count()
这将计算
相同的
酒店联盟
如果它属于
请求.用户
作为
user
. 如果你想数一数
酒店联盟
只有一次,您可以添加
.distinct()
[Django-doc]
致:
HotLeague.objects.filter(user=request.user, match__user=request.user).distinct().count()
或者你可以在
匹配
带有
酒店联盟
由该用户创建,例如:
from django.db.models import Count, Q
matches = Match.objects.filter(user=request.user).annotate(
nhotleagues=Count('hotleague', filter=Q(hotleague__user=request.user))
)
每个
匹配
源于此queryset的,将有一个额外的属性
nhotleagues
指定
酒店联盟
是那个用户的。因此,可以将其渲染为:
{% for match in matches %}
{{ match.pk }}: {{ match.notleagues }}<br>
{% endfor %}
你可以总结一下计数,比如:
from django.db.models import Count, Q
matches = Match.objects.filter(user=request.user).annotate(
total=Count('hotleague', distinct=True, filter=Q(hotleague__user=request.user)) +
Count('mega_league', distinct=True, filter=Q(megaleague__user=request.user)) +
Count('head_to_head_league', distinct=True, filter=Q(head_to_head_league__user=request.user))
)
当然,在联接中添加的表越多,查询的开销就越大。