Helper method. Returns kwargs needed to filter the correct object.

        Can also be used to create the correct object.
498661
def _get_method_kwargs(self):
        
        method_kwargs = {
            'user': self.user,
            'content_type': self.ctype,
            'object_id': self.content_object.pk,
        }
        return method_kwargs
1354515
def find_first_object(self, ObjectClass, **kwargs):
        
        filter = None
        for k, v in kwargs.items():
            cond = getattr(ObjectClass, k) == v
            filter = cond if filter is None else filter & cond

        return list(ObjectClass.scan(filter, limit=1))[0]
763071
def get_query_kwargs(es_defs):
    
    rtn_dict = {}
    if es_defs:
        if es_defs.get("kds_esSpecialUnion"):
            rtn_dict['special_union'] = \
                    es_defs["kds_esSpecialUnion"][0]
        if es_defs.get("kds_esQueryFilter"):
            rtn_dict['filters'] = \
                    es_defs["kds_esQueryFilter"][0]
    return rtn_dict
270799
def get_filterset(self, request, queryset, view):
        
        # TODO: .base_filters vs. .filters attr (not always present)
        filterset_class = self.get_filterset_class(view, queryset)
        kwargs = self.get_filterset_kwargs(request, queryset, view)
        self._validate_filter(kwargs.pop('filter_keys'), filterset_class)
        if filterset_class is None:
            return None
        return filterset_class(**kwargs)
1325765
def process_filter_args(cls, kwargs):
    

    output = {}

    for key, value in kwargs.items():
        if '__' in key:
            prop, operator = key.rsplit('__')
            operator = OPERATOR_TABLE[operator]
        else:
            prop = key
            operator = '='

        if prop not in cls.defined_properties(rels=False):
            raise ValueError("No such property {0} on {1}".format(prop, cls.__name__))

        property_obj = getattr(cls, prop)
        if isinstance(property_obj, AliasProperty):
            prop = property_obj.aliased_to()
            deflated_value = getattr(cls, prop).deflate(value)
        else:
            # handle special operators
            if operator == _SPECIAL_OPERATOR_IN:
                if not isinstance(value, tuple) and not isinstance(value, list):
                    raise ValueError('Value must be a tuple or list for IN operation {0}={1}'.format(key, value))
                deflated_value = [property_obj.deflate(v) for v in value]
            elif operator == _SPECIAL_OPERATOR_ISNULL:
                if not isinstance(value, bool):
                    raise ValueError('Value must be a bool for isnull operation on {0}'.format(key))
                operator = 'IS NULL' if value else 'IS NOT NULL'
                deflated_value = None
            elif operator in _REGEX_OPERATOR_TABLE.values():
                deflated_value = property_obj.deflate(value)
                if not isinstance(deflated_value, basestring):
                    raise ValueError('Must be a string value for {0}'.format(key))
                if operator in _STRING_REGEX_OPERATOR_TABLE.values():
                    deflated_value = re.escape(deflated_value)
                deflated_value = operator.format(deflated_value)
                operator = _SPECIAL_OPERATOR_REGEX
            else:
                deflated_value = property_obj.deflate(value)

        # map property to correct property name in the database
        db_property = cls.defined_properties(rels=False)[prop].db_property or prop

        output[db_property] = (operator, deflated_value)

    return output
162836
def kwargs(self):
        """"""
        # Subclasses must override this property if and only if they define
        # keyword-only arguments in their __init__ method
        if hasattr(self, '_has_kwargs') and self._has_kwargs:
            raise NotImplementedError(
                "Class %s does not provide a kwargs property"
                % str(self.__class__.__name__))
        return {}
1233937
def apply(filter):
    
    def decorator(callable):
        return lambda *args, **kwargs: filter(callable(*args, **kwargs))
    return decorator
735525
def get_or_create(self, **kwargs):
        
        assert kwargs, "get_or_create() must be passed at least one keyword argument"

        defaults = kwargs.pop("defaults", {})
        lookup = kwargs.copy()

        try:
            return self.get(**lookup), False
        except self.resource.DoesNotExist:
            params = dict([(k, v) for k, v in kwargs.items()])
            params.update(defaults)

            obj = self.create(**params)
            return obj, True
856483
def filter(self, *args):
    '''

    '''
    if len(args) == 1 and isinstance(args[0], Filter):
      filter = args[0]
    else:
      filter = Filter(*args)

    # ensure filter gets attr values the same way the rest of the query does.
    filter.object_getattr = self.object_getattr
    self.filters.append(filter)
    return self
1128164
def get_kwargs(self):
        """"""
        return {k: v for k, v in vars(self).items() if k not in self._ignored}
555730
def _get_clean_parameters(kwargs):
        
        return dict((k, v) for k, v in kwargs.items() if v is not None)
758024
def get_filter_options(cls):
        
        attr = '_filter_options_%s' % id(cls)

        options = getattr(cls, attr, {})
        if options:
            return options

        for key in dir(cls):
            val = getattr(cls, key)
            if isinstance(val, FilterOpt):
                options[key] = val

        setattr(cls, attr, options)
        return options
1348430
def create_new_values(self):
        
        model = self.queryset.model
        pks = []
        extra_create_kwargs = self.extra_create_kwargs()
        for value in self._new_values:
            create_kwargs = {self.create_field: value}
            create_kwargs.update(extra_create_kwargs)
            new_item = self.create_item(**create_kwargs)
            pks.append(new_item.pk)
        return model.objects.filter(pk__in=pks)
814064
def get_form_kwargs(self):
        
        kwargs = {"user": self.request.user, "initial": self.get_initial()}
        if self.request.method in ["POST", "PUT"]:
            kwargs.update({
                "data": self.request.POST,
                "files": self.request.FILES,
            })
        return kwargs
588838
def get_filterset_kwargs(self, request, queryset, view):
        
        filter_keys = []
        # rewrite filter[field] query params to make DjangoFilterBackend work.
        data = request.query_params.copy()
        for qp, val in request.query_params.items():
            m = self.filter_regex.match(qp)
            if m and (not m.groupdict()['assoc'] or
                      m.groupdict()['ldelim'] != '[' or m.groupdict()['rdelim'] != ']'):
                raise ValidationError("invalid query parameter: {}".format(qp))
            if m and qp != self.search_param:
                if not val:
                    raise ValidationError("missing {} test value".format(qp))
                # convert jsonapi relationship path to Django ORM's __ notation
                key = m.groupdict()['assoc'].replace('.', '__')
                # undo JSON_API_FORMAT_FIELD_NAMES conversion:
                key = format_value(key, 'underscore')
                data[key] = val
                filter_keys.append(key)
                del data[qp]
        return {
            'data': data,
            'queryset': queryset,
            'request': request,
            'filter_keys': filter_keys,
        }
439338
def get_valid_kwargs(func, potential_kwargs):
    
    kwargs = {}
    for name in get_kwarg_names(func):
        with suppress(KeyError):
            kwargs[name] = potential_kwargs[name]
    return kwargs
92599
def get(cls, **kwargs):
        
        things = cls.filter(**kwargs)
        if len(things) > 1:
            # Raise an exception if more than one object is matched
            raise cls.MultipleObjectsReturned
        elif len(things) == 0:
            # Rase an exception if no objects were matched
            raise cls.DoesNotExist
        return things[0]