from django.db.models import Count from apps.authentication.models import Organization from apps.authentication.services.service import get_all_org_child from apps.herd.models import RancherOrganizationLink class RancherOrganizationService: """ different services of ranchers linked to organization """ def orgs_linked_rancher(self, org: Organization = None, org_type_key: str = None): """ list of organizations with their information of rancher, herd, .... """ if org.type.key != 'ADM': organizations = get_all_org_child(org) organizations = Organization.objects.filter(id__in=[item.id for item in organizations]) else: organizations = Organization.objects.filter(type__key=org_type_key) linked_qs = RancherOrganizationLink.objects.select_related( 'rancher', 'organization' ).filter(organization__in=organizations, organization__type__key=org_type_key) organizations = organizations.annotate( rancher_count=Count( 'rancher_links__rancher', distinct=True ), herd_count=Count( 'rancher_links__rancher__herd', distinct=True ), livestock_count=Count( 'rancher_links__rancher__herd__live_stock_herd', distinct=True ), ) return [ { "id": org.id, "name": org.name, "province": org.province.name, "city": org.city.name, "rancher_count": org.rancher_count, "herd_count": org.herd_count, "livestock_count": org.livestock_count, } for org in organizations ]