def get_filters(cls): """ Get all filters for the filterset. This is the combination of declared and generated filters. """ # No model specified - skip filter generation if not cls._meta.model: return cls.declared_filters.copy() # Determine the filters that should be included on the filterset. filters = OrderedDict() fields = cls.get_fields() undefined = [] for field_name, lookups in fields.items(): field = get_model_field(cls._meta.model, field_name) # warn if the field doesn't exist. if field is None: undefined.append(field_name) for lookup_expr in lookups: filter_name = cls.get_filter_name(field_name, lookup_expr) # If the filter is explicitly declared on the class, skip generation if filter_name in cls.declared_filters: filters[filter_name] = cls.declared_filters[ filter_name] continue if field is not None: filters[filter_name] = cls.filter_for_field( field, field_name, lookup_expr) filters['exclude__{}'.format( filter_name)] = cls.filter_for_field(field, field_name, lookup_expr, exclude=True) # filter out declared filters undefined = [f for f in undefined if f not in cls.declared_filters] if undefined: raise TypeError( "'Meta.fields' contains fields that are not defined on this FilterSet: " "%s" % ', '.join(undefined)) # Add in declared filters. This is necessary since we don't enforce adding # declared filters to the 'Meta.fields' option filters.update(cls.declared_filters) return filters
def __init__(self, fields=None, default=None): self.fields = {} self.subfields = {} self.default = default fields = fields or {} if fields is True: fields = {'ALL': None} if not isinstance(fields, dict): fields = dict([(v, None) for v in fields]) for field, value in fields.items(): try: fieldname, subfield = field.split('__', 1) self.subfields.setdefault(fieldname, {})[subfield] = value except ValueError: self.fields[field] = value
def __init__(self, fields=None, default=None): self.fields = {} self.subfields = {} self.default = default fields = fields or {} if fields is True: fields = {'ALL': None} if not isinstance(fields, dict): fields = dict([(v, None) for v in fields]) for field, value in fields.items(): try: fieldname, subfield = field.split('__', 1) self.subfields.setdefault(fieldname, {})[subfield] = value except ValueError: self.fields[field] = value