首页 > 解决方案 > Django 反向关系(带注释和过滤)

问题描述

我想在特定比赛的“MatchSup”表中获取少于 5 条记录的玩家

Player.objects.filter('age="25"',matchsup__match__in='matchlist').annotate(numviews=Count('matchsup__player__lt=5',)) 像这样(我知道这是错误的)

class Player(models.Model):
    name= models.CharField(max_length=64, null=True, blank=True)
    age=  ...


class MatchSup(models.Model):
    player= models.ForeignKey(Player, null=True, blank=True, on_delete=models.SET_NULL)
    match = models.ForeignKey('Match', on_delete=models.CASCADE)

标签: djangodjango-modelsdjango-views

解决方案


annotate模型上的计数和计数上的Player过滤器:

from django.db.models import Count


Player.objects.filter(
    age=25,
    matchsup__match__in=matchlist
).annotate(
    match_count=Count('matchsup')
).filter(match_count__lt=5)

推荐阅读