def _text_fields_filters(cls, info, filters): name = info['name'] field = info['field'] filters[name] = CharFilter(field_name = field, lookup_expr = 'exact') filters['{}__in'.format(name)] = CharInFilter(field_name = field) for lookup in ('iexact', 'contains', 'icontains', 'startswith', 'istartswith', 'endswith', 'iendswith', 'regex', 'iregex'): filters['{}__{}'.format(name, lookup)] = CharFilter(field_name = field, lookup_expr = lookup)
def _text_fields_filters(cls, info, filters, facade): name = info['name'] field = info['field'] filters[name] = CharFilter(field_name = field, lookup_expr = 'exact') filters["{}__isnull".format(name)] = BooleanFilter(field_name = field, lookup_expr = 'isnull') filters["{}__in".format(name)] = CharInFilter(field_name = field) for lookup in cls._get_text_lookups(): filters['{}__{}'.format(name, lookup)] = CharFilter(field_name = field, lookup_expr = lookup)
def _token_text_filters(cls, info, filters): name = info['name'] field = info['field'] filters[name] = CharFilter(field_name=field, lookup_expr='exact') filters['{}__in'.format(name)] = CharInFilter(field_name=field) for lookup in ('iexact', ): filters['{}__{}'.format(name, lookup)] = CharFilter(field_name=field, lookup_expr=lookup)
def _number_text_filters(cls, info, filters): name = info['name'] field = info['field'] filters[name] = CharFilter(field_name=field, lookup_expr='exact') filters['{}__range'.format(name)] = CharRangeFilter(field_name=field) filters['{}__in'.format(name)] = CharInFilter(field_name=field) for lookup in ('lt', 'lte', 'gt', 'gte'): filters['{}__{}'.format(name, lookup)] = CharFilter(field_name=field, lookup_expr=lookup)
class ContractFilter(ContractBaseFilter, metaclass=MetaFilterSet): vendor = RelatedFilter(VendorFilter) psc_naics = CharFilter(field_name='NAICS', method='filter_psc_naics') class Meta: model = contracts.Contract fields = () def filter_psc_naics(self, qs, name, value): naics_code = re.sub(r'[^\d]+$', '', value) try: naics = categories.Naics.objects.get(code=naics_code) sin_codes = list(naics.sin.all().values_list('code', flat=True)) psc_codes = list( categories.PSC.objects.filter( sin__code__in=sin_codes).distinct().values_list('code', flat=True)) return qs.filter(Q(PSC__in=psc_codes) | Q(NAICS=naics_code)) except Exception: pass return qs.filter(NAICS=naics_code)
class ContractFilter(FilterSet, metaclass=MetaFilterSet): _token_text = ('agency_id', ) _fuzzy_text = ('piid', 'agency_name', 'NAICS', 'PSC', 'point_of_contact', 'vendor_phone') _number = ('id', 'obligated_amount', 'annual_revenue', 'number_of_employees') _date_time = ('date_signed', 'completion_date') status = RelatedFilter(ContractStatusFilter) pricing_type = RelatedFilter(PricingStructureFilter) vendor = RelatedFilter(VendorFilter) vendor_location = RelatedFilter(LocationFilter) place_of_performance = RelatedFilter(PlaceOfPerformanceFilter) psc_naics = CharFilter(field_name='NAICS', method='filter_psc_naics') class Meta: model = contracts.Contract fields = () def filter_psc_naics(self, qs, name, value): naics_code = re.sub(r'[^\d]+$', '', value) psc_codes = list( categories.PSC.objects.filter( naics__root_code=naics_code).distinct().values_list('code', flat=True)) return qs.filter(Q(PSC__in=psc_codes) | Q(NAICS=naics_code))
def _time_fields_filters(cls, info, filters): name = info['name'] field = info['field'] filters[name] = CharFilter(field_name = field, lookup_expr = 'startswith') for lookup in ('year', 'month', 'day', 'week', 'week_day', 'quarter'): filters['{}__{}'.format(name, lookup)] = NumberFilter(field_name = field, lookup_expr = lookup)
class ArtistFilter(filters.FilterSet): name = CharFilter(field_name='name', lookup_expr='iexact') class Meta: model = Artist fields = { 'name': ['iexact', 'in', 'startswith', 'icontains'], }
class DJFilter(filters.FilterSet): name = CharFilter(field_name='name', lookup_expr='iexact') setlists = filters.RelatedFilter('SetlistFilter', field_name='setlists', queryset=Setlist.objects.all()) class Meta: model = DJ fields = { 'name': ['iexact', 'in', 'startswith', 'icontains'], }
class LabelFilter(filters.FilterSet): name = CharFilter(field_name='name', lookup_expr='iexact') track_plays = filters.RelatedFilter('TrackPlayFilter', field_name='track_plays', queryset=TrackPlay.objects.all()) class Meta: model = Label fields = { 'name': ['iexact', 'in', 'startswith', 'icontains'], }
class TrackFilter(filters.FilterSet): title = CharFilter(field_name='title', lookup_expr='iexact') artist = filters.RelatedFilter('ArtistFilter', field_name='artist', queryset=Artist.objects.all()) setlists = filters.RelatedFilter('SetlistFilter', field_name='setlists', queryset=Setlist.objects.all()) plays = filters.RelatedFilter('TrackPlayFilter', field_name='plays', queryset=TrackPlay.objects.all()) class Meta: model = Track fields = { 'title': ['iexact', 'in', 'startswith', 'icontains'], }
class SetlistFilter(filters.FilterSet): title = CharFilter(field_name='title', lookup_expr='iexact') dj = filters.RelatedFilter('DJFilter', field_name='dj', queryset=DJ.objects.all()) track_plays = filters.RelatedFilter('TrackPlayFilter', field_name='track_plays', queryset=TrackPlay.objects.all()) empty = BooleanFilter(field_name='empty', method='filter_empty') def filter_empty(self, qs, name, value): return qs.filter(track_plays__isnull=value) class Meta: model = Setlist fields = { # 'dj__name': ['iexact', 'in', 'startswith', 'icontains'], 'title': ['iexact', 'in', 'startswith', 'icontains'], 'mixesdb_id': ['exact', 'in'], 'b2b': ['exact'], }
def _time_fields_filters(cls, info, filters, facade): name = info['name'] field = info['field'] filters[name] = CharFilter(field_name = field, lookup_expr = 'startswith') filters["{}__isnull".format(name)] = BooleanFilter(field_name = field, lookup_expr = 'isnull') filters["{}__time".format(name)] = DateTimeFilter(field_name = field, lookup_expr = 'time') filters["{}__in".format(name)] = DateTimeInFilter(field_name = field) filters["{}__range".format(name)] = DateTimeRangeFilter(field_name = field) for lookup in cls._get_number_lookups(): filters["{}__{}".format(name, lookup)] = DateTimeFilter(field_name = field, lookup_expr = lookup) for lookup in cls._get_time_lookups(): filters["{}__{}".format(name, lookup)] = NumberFilter(field_name = field, lookup_expr = lookup) filters["{}__{}__in".format(name, lookup)] = NumberInFilter(field_name = field) filters["{}__{}__range".format(name, lookup)] = NumberRangeFilter(field_name = field) for sub_lookup in cls._get_number_lookups(): full_lookup = "{}__{}".format(lookup, sub_lookup) filters["{}__{}".format(name, full_lookup)] = NumberFilter(field_name = field, lookup_expr = full_lookup)
class VendorFilter(VendorBaseFilter): contract = RelatedFilter("ContractBaseFilter") membership = CharFilter(field_name='membership', method='filter_membership') def filter_membership(self, qs, name, value): # Decode complex membership query try: complex_ops = decode_complex_ops(value, filter_operators(), True) except ValidationError as exc: raise ValidationError({'membership': exc.detail}) # Collect the individual filtered membership querysets querystrings = [op.querystring for op in complex_ops] ms_queryset = vendors.PoolMembership.objects.all() ms_querysets = [] errors = [] for qstring in querystrings: query = qstring.split('=') try: ms_querysets.append(ms_queryset.filter(**{query[0]: query[1]})) except ValidationError as exc: errors[qstring] = exc.detail if errors: raise ValidationError(errors) # Retrieve a list of membership ids matching query ms_queryset = combine_complex_queryset(ms_querysets, complex_ops) ms_ids = list(ms_queryset.values_list('id', flat=True)) # Filter vendors by membership if len(querystrings) > 0: qs = qs.filter(pools__id__in=ms_ids) return qs
class VendorFilter(VendorBaseFilter): contract = RelatedFilter("ContractBaseFilter") membership = CharFilter(field_name='membership', method='filter_membership') def getMebershipIds(self, poolVehcileId, poolIds): ms_ids = list() ms_queryset = vendors.PoolMembership.objects.filter( pool__id__in=poolIds, pool__vehicle__id=poolVehcileId).only("vendor_id", "pool_id") vendorIdsByPool = {} poolMembershipIdsByVendors = {} for membership in ms_queryset: if membership.pool_id in vendorIdsByPool: vendorIdsByPool[membership.pool_id].add(membership.vendor_id) else: vendorIds = set() vendorIds.add(membership.vendor_id) vendorIdsByPool[membership.pool_id] = vendorIds if membership.vendor_id in poolMembershipIdsByVendors: poolMembershipIdsByVendors[membership.vendor_id].append( membership.id) else: membershipIds = [membership.id] poolMembershipIdsByVendors[ membership.vendor_id] = membershipIds vendorIdIntersections = set() checkFirstIteration = True for key in vendorIdsByPool: if checkFirstIteration: vendorIdIntersections = vendorIdsByPool.get(key) checkFirstIteration = False else: vendorIdIntersections = vendorIdIntersections & vendorIdsByPool.get( key) for vendorId in vendorIdIntersections: ms_ids.extend(poolMembershipIdsByVendors.get(vendorId)) return ms_ids def filter_membership(self, qs, name, value): try: complex_ops = decode_complex_ops(value, filter_operators(), True) except ValidationError as exc: raise ValidationError({'membership': exc.detail}) # Collect the individual filtered membership querysets querystrings = [op.querystring for op in complex_ops] ms_queryset = vendors.PoolMembership.objects.all() ms_querysets = [] errors = [] poolIds = [] queryParameters = {} for qstring in querystrings: query = qstring.split('=') try: queryParameters[query[0]] = query[1] ms_querysets.append(ms_queryset.filter(**{query[0]: query[1]})) except ValidationError as exc: errors[qstring] = exc.detail if 'pool__id' in queryParameters.keys(): poolIds = queryParameters.get('pool__id').split(",") if (len(poolIds) <= 1): try: ms_queryset = combine_complex_queryset(ms_querysets, complex_ops) ms_ids = list(ms_queryset.values_list('id', flat=True)) except ValidationError as exc: errors[qstring] = exc.detail else: try: poolVehcileId = queryParameters.get('pool__vehicle__id') ms_ids = self.getMebershipIds(poolVehcileId, poolIds) if len(ms_ids) == 0: qs = qs.filter(pools__id=0) return qs except ValidationError as exc: errors[qstring] = exc.detail if errors: raise ValidationError(errors) if len(querystrings) > 0: qs = qs.filter(pools__id__in=ms_ids) return qs