如何从Django中的ManyToManyField计算查询集?

时间:2019-07-09 12:38:02

标签: django django-models django-views

在型号中:

class Match(models.Model):
    user = models.ManyToManyField(User, blank=True)
    hot_league = models.ManyToManyField('HotLeague', blank=True)

class HotLeague(models.Model):
    user = models.ManyToManyField(User, blank=True)
    price_pool = models.IntegerField()
    winner = models.IntegerField()

在视图中:

match = Match.objects.filter(user=request.user)
hot_league = match.hot_league.filter(user=request.user).count()

此处的视图count()无法正常工作。 如何计算hot_league中的match

1 个答案:

答案 0 :(得分:0)

这里的问题是match不是一个Match对象,而是一个QuerySet,其中包含零个,一个或多个{{1} }对象。因此,不能在此类Match上使用hot_league关系。

如果您要计算属于QuerySet的所有HotLeague,并且也有属于该request.user的{​​{1}},则可以计算此为:

Match

如果相同 request.user属于多个匹配项,且HotLeague.objects.filter(user=request.user, match__user=request.user).count()HotLeague,则它将多次计数。如果您只希望对每个request.user进行一次计数,则可以在其中添加一个.distinct() [Django-doc]

user

或者您可以用该用户的HotLeague数来注释HotLeague.objects.filter(user=request.user, match__user=request.user).distinct().count()的数目,例如:

Match

源自此查询集的每个HotLeague将具有一个额外的属性from django.db.models import Count, Q matches = Match.objects.filter(user=request.user).annotate( nhotleagues=Count('hotleague', filter=Q(hotleague__user=request.user)) ),该属性指定该用户的Match个数目。因此,您可以将其呈现为:

nhotleagues

您可以汇总计数,例如:

HotLeague

当然,在JOIN中添加的表越多,查询的开销就越大。

相关问题