社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Django

如何计算django ManyToManyField的queryset?

jhon arab • 6 年前 • 1984 次点击  

在模型中:

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 ??

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/50984
文章 [ 1 ]  |  最新文章 6 年前
Willem Van Onsem
Reply   •   1 楼
Willem Van Onsem    7 年前

问题是 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))
)

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