Remove unwanted results from queryset
779698
def filter_out(queryset, setting_name):
  
  kwargs = helpers.get_settings().get(setting_name, {}).get('FILTER_OUT', {})
  queryset = queryset.exclude(**kwargs)
  return queryset
1248609
def delete(self):
        
        assert self.query.can_filter(), \
            "Cannot use 'limit' or 'offset' with delete."

        # Ensure that only current objects are selected.
        del_query = self.filter(version_end_date__isnull=True)

        # The delete is actually 2 queries - one to find related objects,
        # and one to delete. Make sure that the discovery of related
        # objects is performed on the same database as the deletion.
        del_query._for_write = True

        # Disable non-supported fields.
        del_query.query.select_for_update = False
        del_query.query.select_related = False
        del_query.query.clear_ordering(force_empty=True)

        collector_class = get_versioned_delete_collector_class()
        collector = collector_class(using=del_query.db)
        collector.collect(del_query)
        collector.delete(get_utc_now())

        # Clear the result cache, in case this QuerySet gets reused.
        self._result_cache = None
646908
def cleanup_relations(self):
        """"""
        collections = self.collections
        for relation in [x for col in collections.values()
                         for x in col.model.relations.values()]:
            db.session.query(relation)\
                       .filter(~relation.listing.any())\
                       .delete(synchronize_session=False)
        db.session.commit()
77011
def clean(self):
        
        if self.lookup == '?':  # Randomly sort
            return
        else:
            lookups = self.lookup.split(LOOKUP_SEP)
            opts = self.model_def.model_class()._meta
            valid = True
            while len(lookups):
                lookup = lookups.pop(0)
                try:
                    field = opts.get_field(lookup)
                except FieldDoesNotExist:
                    valid = False
                else:
                    if isinstance(field, models.ForeignKey):
                        opts = get_remote_field_model(field)._meta
                    elif len(lookups):  # Cannot go any deeper
                        valid = False
                finally:
                    if not valid:
                        msg = _("This field doesn't exist")
                        raise ValidationError({'lookup': [msg]})
357099
def cleanup_datastore(self):
    """"""
    print_header('CLEANING UP ENTIRE DATASTORE')
    kinds_to_delete = [u'Submission', u'SubmissionType',
                       u'DatasetImage', u'DatasetBatch',
                       u'AdversarialImage', u'AdversarialBatch',
                       u'Work', u'WorkType',
                       u'ClassificationBatch']
    keys_to_delete = [e.key for k in kinds_to_delete
                      for e in self.datastore_client.query_fetch(kind=k)]
    self._cleanup_keys_with_confirmation(keys_to_delete)
496859
def unmark_featured(self, request, queryset):
        
        queryset.update(featured=False)
        self.message_user(
            request, _('Selected entries are no longer marked as featured.'))
196624
def delete_one(self, query):
        
        item = self.find_one(query)
        result = self.table.remove(where(u'_id') == item[u'_id'])

        return DeleteResult(raw_result=result)
1237574
def remove_query_param(self, key, value=None):
        
        parse_result = self.query_params()
        if value is not None:
            index = parse_result[key].index(value)
            del parse_result[key][index]
        else:
            del parse_result[key]
        return URL._mutate(self, query=unicode_urlencode(parse_result, doseq=True))
452870
def clean_before_output(kw_matches):
    
    filtered_kw_matches = {}

    for kw_match, info in iteritems(kw_matches):
        if not kw_match.nostandalone:
            filtered_kw_matches[kw_match] = info

    return filtered_kw_matches
84721
private QueryResultImpl eliminateDuplicates(QueryResultImpl result) {
        QueryResultImpl ret = new QueryResultImpl(result.getQuery());
        Set<QueryBindingImpl> distinctSet = new HashSet<>(result.getBindings());
        distinctSet.forEach(ret::add);
        return ret;
    }
616048
def filter_facet_queryset(self, queryset):
        
        for backend in list(self.facet_filter_backends):
            queryset = backend().filter_queryset(self.request, queryset, self)

        if self.load_all:
            queryset = queryset.load_all()

        return queryset
1227139
def _filter_or_exclude_querysets(self, negate, **kwargs):
        
        # Ensure negate is a boolean.
        negate = bool(negate)

        for kwarg, value in kwargs.items():
            parts = kwarg.split(LOOKUP_SEP)

            # Ensure this is being used to filter QuerySets.
            if parts[0] != '#':
                raise ValueError("Keyword '%s' is not a valid keyword to filter over, "
                                 "it must begin with '#'." % kwarg)

            # Don't allow __ multiple times.
            if len(parts) > 2:
                raise ValueError("Keyword '%s' must not contain multiple "
                                 "lookup seperators." % kwarg)

            # The actual lookup is the second part.
            try:
                lookup = parts[1]
            except IndexError:
                lookup = 'exact'

            # Math operators that all have the same logic.
            LOOKUP_TO_OPERATOR = {
                'exact': eq,
                'iexact': eq,
                'gt': gt,
                'gte': ge,
                'lt': lt,
                'lte': le,
            }
            try:
                operator = LOOKUP_TO_OPERATOR[lookup]

                # These expect integers, this matches the logic in
                # IntegerField.get_prep_value(). (Essentially treat the '#'
                # field as an IntegerField.)
                if value is not None:
                    value = int(value)

                self._queryset_idxs = filter(lambda i: operator(i, value) != negate, self._queryset_idxs)
                continue
            except KeyError:
                # It wasn't one of the above operators, keep trying.
                pass

            # Some of these seem to get handled as bytes.
            if lookup in ('contains', 'icontains'):
                value = six.text_type(value)
                self._queryset_idxs = filter(lambda i: (value in six.text_type(i)) != negate, self._queryset_idxs)

            elif lookup == 'in':
                self._queryset_idxs = filter(lambda i: (i in value) != negate, self._queryset_idxs)

            elif lookup in ('startswith', 'istartswith'):
                value = six.text_type(value)
                self._queryset_idxs = filter(lambda i: six.text_type(i).startswith(value) != negate, self._queryset_idxs)

            elif lookup in ('endswith', 'iendswith'):
                value = six.text_type(value)
                self._queryset_idxs = filter(lambda i: six.text_type(i).endswith(value) != negate, self._queryset_idxs)

            elif lookup == 'range':
                # Inclusive include.
                start, end = value
                self._queryset_idxs = filter(lambda i: (start <= i <= end) != negate, self._queryset_idxs)

            else:
                # Any other field lookup is not supported, e.g. date, year, month,
                # day, week_day, hour, minute, second, isnull, search, regex, and
                # iregex.
                raise ValueError("Unsupported lookup '%s'" % lookup)

        # Convert back to a list on Python 3.
        self._queryset_idxs = list(self._queryset_idxs)

        # Finally, keep only the QuerySets we care about!
        self._querysets = [self._querysets[i] for i in self._queryset_idxs]
646691
def exclude_current_instance(self, queryset):
        
        if self.instance is not None:
            return queryset.exclude(pk=self.instance.pk)
        return queryset
851039
def filter_queryset(self, request, queryset, view):
        
        # Check if this is a list type request
        if view.lookup_field not in view.kwargs:
            if not self.action_routing:
                return self.filter_list_queryset(request, queryset, view)
            else:
                method_name = "filter_{action}_queryset".format(action=view.action)
                return getattr(self, method_name)(request, queryset, view)
        return queryset
1144945
static void filterUnwantedReferences(List<JpaRef> result, Collection<BeanId> query) {
        ListIterator<JpaRef> it = result.listIterator();
        while (it.hasNext()) {
            // remove reference from result that was not part of the query
            BeanId found = it.next().getSource();
            if (!query.contains(found)) {
                it.remove();
            }
        }
    }
415913
def remove(self, _query=None, **kwargs):
        
        for entry in self._find_entries(_query=_query, **kwargs):
            self._service.DeleteRow(entry)
239173
def filter(self, *args, **kwargs) -> "QuerySet":
        
        return self._filter_or_exclude(negate=False, *args, **kwargs)