Ticket #12173: filterspec_or_support.patch

File filterspec_or_support.patch, 2.1 KB (added by Fabián Ezequiel Gallina, 15 years ago)

first proposal to support OR in filterspecs

  • django/contrib/admin/views/main.py

     
    2727TO_FIELD_VAR = 't'
    2828IS_POPUP_VAR = 'pop'
    2929ERROR_FLAG = 'e'
     30FILTERSPEC_OR_PREFIX = '__or__'
    3031
    3132# Text to display within change-list table cells if the value is blank.
    3233EMPTY_CHANGELIST_VALUE = '(None)'
     
    8788        p = self.params.copy()
    8889        for r in remove:
    8990            for k in p.keys():
    90                 if k.startswith(r):
     91                if k.startswith(r) or k.startswith(FILTERSPEC_OR_PREFIX):
    9192                    del p[k]
    9293        for k, v in new_params.items():
    9394            if v is None:
     
    187188
    188189        # Apply lookup parameters from the query string.
    189190        try:
    190             qs = qs.filter(**lookup_params)
     191            or_params = {}
     192            and_params = lookup_params
     193            for key, value in lookup_params.items():
     194                if key.startswith(FILTERSPEC_OR_PREFIX):
     195                    or_params[key[len(FILTERSPEC_OR_PREFIX):]] = and_params.pop(key)
     196
     197            if or_params:
     198                and_queries = [models.Q(**{key: value}) for key, value in and_params.items()]
     199                or_queries = [models.Q(**{key: value}) for key, value in or_params.items()]
     200                if and_queries:
     201                    qs = qs.filter(reduce(operator.and_, and_queries) | reduce(operator.or_, or_queries))
     202            else:
     203                qs = qs.filter(**lookup_params)
     204
    191205        # Naked except! Because we don't have any other way of validating "params".
    192206        # They might be invalid if the keyword arguments are incorrect, or if the
    193207        # values are not in the correct type, so we might get FieldError, ValueError,
    194         # ValicationError, or ? from a custom field that raises yet something else
     208        # ValidationError, or ? from a custom field that raises yet something else
    195209        # when handed impossible data.
    196210        except:
    197211            raise IncorrectLookupParameters
Back to Top