queryset_utils.py 2.1 KB

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