For the admin section I found hacky way to do it. My example is with admin.StackedInline, but almost sure it will work with plain ModelAdmin. I left it here just in case someone likes this solution:
class ProfessionalInline(admin.StackedInline):
model = Professional
fieldsets = [
('Research information', {
'fields': ('team', 'projects')
}),
('Profile information', {
'fields': ('age', 'gender', 'receive_emails')
})]
def get_parent_object_from_request(self, request):
"""
Returns the parent object from the request or None.
Note that this only works for Inlines, because the `parent_model`
is not available in the regular admin.ModelAdmin as an attribute.
"""
resolved = resolve(request.path_info)
if resolved.kwargs:
return self.parent_model.objects.get(pk=resolved.kwargs['object_id'])
return None
def formfield_for_manytomany(self, db_field, request, **kwargs):
'''Extremely hacky'''
account = self.get_parent_object_from_request(request)
if db_field.name == 'projects':
kwargs['queryset'] = Project.objects.filter(team=account.professional.team)
return super().formfield_for_manytomany(db_field, request, **kwargs)