开发者

How to filter a django queryset based on the number of many-to-many relationships?

I have the following situ开发者_开发知识库ation: A person can belong to multiple organizations and an organization can have multiple members (Persons)

class Person(models.Model):

    organizations = ManytoManyField(Organization)

I want to classify the Organizations by number of members:

Organizations with 0 members

Organizations with 1 member

Organizations with 5 members or more and so on.

For each of these categories I only want to use one query to the database. This means that I don't want to use for-loops at all for performance reasons.

In the end the question is: How can I filter a django queryset based on the number of manytomany relationships it has?

Thanks


Use Django aggregations over QuerySets, especially Count.

from django.db.models import Count
Person.objects.aggregate(Count('organizations'))

More on this topic: https://docs.djangoproject.com/en/dev/topics/db/aggregation/

(But I also think that there is a .Count() or something abbreviation like that somewhere.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜