Django:在模型的ManyToMany中使用的计数用户

时间:2014-08-14 12:48:54

标签: python sql django

给出一个模型:

class Workshop(models.Model):
    title = models.CharField(max_length=40)
    participants = models.ManyToManyField(User, null=True, blank=True)

(用户是django.contrib.auth.models.User)

用户可以参加多个研讨会:

  • w1.participants =(u1,u2)

  • w2.participants =(u2,u3)

  • ...

我需要找到:
1)参加1个研讨会的用户数量(u1,u3)
2)参加2个研讨会的用户数量(u2)
3)未参加任何研讨会的用户(u0)

有人可以帮我吗?
提前非常感谢你!

2 个答案:

答案 0 :(得分:2)

试试这个:

from django.db.models import Count

1)

User.objects.annotate(workshop_count=Count('workshop')).filter(workshop_count=1).count()

2)

User.objects.annotate(workshop_count=Count('workshop')).filter(workshop_count=2).count()

3)

User.objects.filter(workshop__isnull=True).count()

More info in the docs

答案 1 :(得分:0)

这应该做你想要的:

workshop_user_dict = {}
user_objects = User.objects.all()
for user in user_objects:
     workshops_count = user.workshop_set.all().count()
     if not workshops_count in workshop_user_dict:
         workshop_user_dict[workshops_count] = []
     workshop_user_dict[workshops_count].append(user)


for key, list in workshop_user_dict.items():
    print 'There are ' + str(len(list)) + ' users that are participating in ' + str(key) +  ' workshops'