2👍
✅
Use annotate for group by:
from django.db.models import Count
#group by portfolios count
User.objects.annotate(portfolios=Count('portfolio')).order_by('portfolios')
#group by projects count
User.objects.annotate(projects=Count('portfolio__project')).order_by('projects')
👤ndpu
Source:stackexchange.com