queryset_utils.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. from django.db.models import Count, Exists, OuterRef, Prefetch, Subquery
  2. from apps.projects.models import Project
  3. from apps.teams.models import Team
  4. from .models import Organization, OrganizationUser
  5. def get_organizations_queryset(user_id, role_required=False, add_details=False):
  6. qs = Organization.objects.filter(users=user_id)
  7. if role_required:
  8. qs = qs.annotate(
  9. actor_role=Subquery(
  10. qs.filter(organization_users__user=user_id).values(
  11. "organization_users__role"
  12. )[:1]
  13. )
  14. )
  15. if add_details:
  16. qs = qs.prefetch_related(
  17. Prefetch(
  18. "projects",
  19. queryset=Project.annotate_is_member(Project.objects, user_id),
  20. ),
  21. "projects__teams",
  22. Prefetch(
  23. "teams",
  24. queryset=Team.objects.annotate(
  25. is_member=Exists(
  26. OrganizationUser.objects.filter(
  27. teams=OuterRef("pk"), user_id=user_id
  28. )
  29. ),
  30. member_count=Count("members"),
  31. ),
  32. ),
  33. "teams__members",
  34. )
  35. return qs
  36. def get_organization_users_queryset(
  37. user_id: int,
  38. organization_slug: str,
  39. team_slug: str | None = None,
  40. role_required=False,
  41. add_details=False,
  42. ):
  43. qs = (
  44. OrganizationUser.objects.filter(
  45. organization__users=user_id, organization__slug=organization_slug
  46. )
  47. .select_related("user")
  48. .prefetch_related("user__socialaccount_set")
  49. )
  50. if team_slug:
  51. qs = qs.filter(teams__slug=team_slug)
  52. if role_required:
  53. qs = qs.annotate(
  54. actor_role=Subquery(
  55. qs.filter(organization__organization_users__user=user_id).values(
  56. "organization__organization_users__role"
  57. )[:1]
  58. )
  59. )
  60. if add_details:
  61. qs = qs.select_related("organization__owner").prefetch_related("teams")
  62. return qs