如何对两个ManyToMany字段中的不同行进行计数

问题描述 投票:1回答:1
from django.db import models

class Group(models.Model):
  users = models.ManyToMany(User, blank=True, related_name="groups"


class Task(models.Model):
  users = models.ManyToManyField(User, blank=True, related_name="personal_tasks")
  groups = models.ManyToManyField(Group, blank=True, related_name="group_tasks")

注:上面的代码是为了演示概念,不是正在使用的代码。

因此,以上述模型为例,是否有可能(最好使用单个查询)获得唯一身份用户的总数?

[起初我只是想将users字段和groups__users字段的计数相加,但是,我想考虑有人既通过个人又通过他们的组来分配任务的可能性。

python django many-to-many django-orm
1个回答
0
投票

如果您使用基于CBv类的视图!!

在Views.py中:

class yourclass(ListView):
    model = YourModel
    template_name = '....'
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['Count_Somthing'] = YourModel.objects.all().count()
        return context   

在您的模板html中使用:{{Count_Somthing}}

如果使用Function:使用过滤器很容易

def Your_Fonction(request):
    search_for= YourModel.objects.get(any_fields= pk)
    Count_Somthing=search_for.count()
  return(request,'....html',Count_Somthing)

在您的模板html中使用:{{Count_Somthing}}

© www.soinside.com 2019 - 2024. All rights reserved.