bennylope / django-organizations

:couple: Multi-user accounts for Django projects
http://django-organizations.readthedocs.org/
BSD 2-Clause "Simplified" License
1.31k stars 212 forks source link

How do you get the User's organizations? #148

Closed specialorange closed 6 years ago

specialorange commented 6 years ago

https://stackoverflow.com/questions/48852913/get-users-organizations-in-django-organizations

For the app django-organizations, how do you get a User's organization? From the docs it says

>>> from organizations.utils import create_organization
>>> chris = User.objects.get(username="chris")
>>> soundgarden = create_organization(chris, "Soundgarden", org_user_defaults={'is_admin': True})
>>> soundgarden.is_member(chris)
True
>>> soundgarden.is_admin(chris)
True
>>> soundgarden.owner.organization_user
<OrganizationUser: Chris Cornell>
>>> soundgarden.owner.organization_user.user
>>> <User: chris>
>>> audioslave = create_organization(chris, "Audioslave")
>>> tom = User.objects.get(username="tom")
>>> audioslave.add_user(tom, is_admin=True)
<OrganizationUser: Tom Morello>

and in my code I can easily do :

@login_required
def bandView(request, bandSlug):   
  loggedInUser = get_object_or_404(User, username=request.user.get_username())
  organization_requested = get_object_or_404(Organization, slug=bandSlug)
  if organization_requested.is_member(loggedInUser):
    #User is a member of the organization
  elze:
    # Not in this band

but I am trying to work the other way now:

@login_required
def artistView(request):   
  loggedInUser = get_object_or_404(User, username=request.user.get_username())
  #something like....
  loggedInUser.organizations #would print [<band1>,<band2>]
  #or add a function to the Organization[User] class
  Organizations.all().filter(member=loggedInuser)
  Organizations.getMembership(loggedInuser)

Notes

yvsssantosh commented 6 years ago

After searching this repo I found this https://github.com/bennylope/django-organizations/blob/9058331e9ab8f1ce4b81b89cbc33211c113e4427/docs/reference/managers.rst

Is that what you were trying to do @specialorange ?

bennylope commented 6 years ago

@specialorange had answered his question on the SO question linked above, but in a nutshell the original problem was missing the queryset method on the reverse relation manager.

My added comment on SO:

That's exactly it. organizations_organization is the named reverse relationship through the OrganizationUser model (which is the linking or intermediate model) to the User model. That just returns the RelatedManager and then from that manager you can call different query methods (e.g. all, filter, etc).