<s> import datetime <EOL> import operator <EOL> import re <EOL> from functools import reduce <EOL> from dateutil . relativedelta import relativedelta <EOL> from django . db . models import Q <EOL> FILTER_FROM_NOW = re . compile ( r'<STR_LIT>' ) <EOL> class FilterParser ( object ) : <EOL> def __init__ ( self , queryset , filters_dict , exclude_mode = False ) : <EOL> self . filters = filters_dict <EOL> if exclude_mode : <EOL> self . queryset_func = queryset . exclude <EOL> else : <EOL> self . queryset_func = queryset . filter <EOL> def get_queryset ( self ) : <EOL> parsed_kwargs = { } <EOL> parsed_args = [ ] <EOL> for key , value in self . filters . items ( ) : <EOL> params = key . split ( '<STR_LIT:|>' ) <EOL> if len ( params ) == <NUM_LIT:1> : <EOL> parsed_kwargs [ key ] = value <EOL> elif len ( params ) == <NUM_LIT:2> : <EOL> filter_func = getattr ( self , '<STR_LIT>' + params [ <NUM_LIT:1> ] , None ) <EOL> if not filter_func : <EOL> continue <EOL> args , kwargs = filter_func ( params [ <NUM_LIT:0> ] , value ) <EOL> parsed_args . extend ( args ) <EOL> parsed_kwargs . update ( kwargs ) <EOL> else : <EOL> continue <EOL> return self . queryset_func ( * parsed_args , ** parsed_kwargs ) <EOL> def _filter_operator ( self , key , value , op ) : <EOL> return reduce ( op , [ Q ( ** { key : v } ) for v in value ] ) <EOL> def filter_or ( self , key , value ) : <EOL> return [ self . _filter_operator ( key , value , operator . or_ ) ] , { } <EOL> def filter_and ( self , key , value ) : <EOL> return [ self . _filter_operator ( key , value , operator . and_ ) ] , { } <EOL> def filter_from_now ( self , key , value ) : <EOL> period_mapper = { <EOL> '<STR_LIT:d>' : '<STR_LIT>' , <EOL> '<STR_LIT:m>' : '<STR_LIT>' , <EOL> '<STR_LIT:y>' : '<STR_LIT>' , <EOL> } <EOL> val , period = FILTER_FROM_NOW . match ( value ) . groups ( ) <EOL> result = datetime . date . today ( ) + relativedelta ( ** { <EOL> period_mapper . get ( period ) : int ( val ) <EOL> } ) <EOL> return [ ] , { key : result . strftime ( '<STR_LIT>' ) } </s>
