<s> from sqlalchemy import or_ <EOL> from flask_admin . _compat import as_unicode , string_types <EOL> from flask_admin . model . ajax import AjaxModelLoader , DEFAULT_PAGE_SIZE <EOL> from . tools import get_primary_key , has_multiple_pks <EOL> class QueryAjaxModelLoader ( AjaxModelLoader ) : <EOL> def __init__ ( self , name , session , model , ** options ) : <EOL> """<STR_LIT>""" <EOL> super ( QueryAjaxModelLoader , self ) . __init__ ( name , options ) <EOL> self . session = session <EOL> self . model = model <EOL> self . fields = options . get ( '<STR_LIT>' ) <EOL> self . order_by = options . get ( '<STR_LIT>' ) <EOL> if not self . fields : <EOL> raise ValueError ( '<STR_LIT>' % ( model , self . name ) ) <EOL> self . _cached_fields = self . _process_fields ( ) <EOL> if has_multiple_pks ( model ) : <EOL> raise NotImplementedError ( '<STR_LIT>' ) <EOL> self . pk = get_primary_key ( model ) <EOL> def _process_fields ( self ) : <EOL> remote_fields = [ ] <EOL> for field in self . fields : <EOL> if isinstance ( field , string_types ) : <EOL> attr = getattr ( self . model , field , None ) <EOL> if not attr : <EOL> raise ValueError ( '<STR_LIT>' % ( self . model , field ) ) <EOL> remote_fields . append ( attr ) <EOL> else : <EOL> remote_fields . append ( field ) <EOL> return remote_fields <EOL> def format ( self , model ) : <EOL> if not model : <EOL> return None <EOL> return ( getattr ( model , self . pk ) , as_unicode ( model ) ) <EOL> def get_one ( self , pk ) : <EOL> return self . session . query ( self . model ) . get ( pk ) <EOL> def get_list ( self , term , offset = <NUM_LIT:0> , limit = DEFAULT_PAGE_SIZE ) : <EOL> query = self . session . query ( self . model ) <EOL> filters = ( field . ilike ( u'<STR_LIT>' % term ) for field in self . _cached_fields ) <EOL> query = query . filter ( or_ ( * filters ) ) <EOL> if self . order_by : <EOL> query = query . order_by ( self . order_by ) <EOL> return query . offset ( offset ) . limit ( limit ) . all ( ) <EOL> def create_ajax_loader ( model , session , name , field_name , options ) : <EOL> attr = getattr ( model , field_name , None ) <EOL> if attr is None : <EOL> raise ValueError ( '<STR_LIT>' % ( model , field_name ) ) <EOL> if not hasattr ( attr , '<STR_LIT>' ) or not hasattr ( attr . property , '<STR_LIT>' ) : <EOL> raise ValueError ( '<STR_LIT>' % ( model , field_name ) ) <EOL> remote_model = attr . prop . mapper . class_ <EOL> return QueryAjaxModelLoader ( name , session , remote_model , ** options ) </s>
