Build ``query_string`` object from ``q``.

    :param q: q of type String
    :param default_field: default_field
    :return: dictionary object.
1991
def _build_query_string(q, default_field=None, default_operator='AND'):
    
    def _is_phrase_search(query_string):
        clean_query = query_string.strip()
        return clean_query and clean_query.startswith('"') and clean_query.endswith('"')

    def _get_phrase(query_string):
        return query_string.strip().strip('"')

    if _is_phrase_search(q):
        query = {'match_phrase': {'_all': _get_phrase(q)}}
    else:
        query = {'query_string': {'query': q, 'default_operator': default_operator}}
        query['query_string'].update({'lenient': False} if default_field else {'default_field': default_field})

    return query
1199054
def get_queryset(qs=None, app=DEFAULT_APP, db_alias=None):
    
    # app = get_app(app);
    # print 'get_model' + repr(model) + ' app ' + repr(app)
    if isinstance(qs, (djmodels.Manager, djmodels.query.QuerySet)):
        qs = qs.all()
    else:
        qs = get_model(qs, app=app).objects.all()
    if db_alias:
        return qs.using(db_alias)
    else:
        return qs
654406
def ask_str(question: str, default: str = None):
    """"""
    default_q = " [default: {0}]: ".format(
        default) if default is not None else ""
    answer = input("{0} [{1}]: ".format(question, default_q))

    if answer == "":
        return default
    return answer
1100948
def _split_url_string(query_string):
        
        parameters = parse_qs(to_utf8(query_string), keep_blank_values=True)
        for k, v in parameters.iteritems():
            parameters[k] = urllib.unquote(v[0])
        return parameters
77327
def parse_querystring(self, req, name, field):
        """"""
        return core.get_value(req.params, name, field)
797721
def get_parameters_as_dictionary(self, query_string):
        
        pairs = (x.split('=', 1) for x in query_string.split('&'))
        return dict((k, unquote(v)) for k, v in pairs)
648033
def build_db_query(fields_names, field_values):
    
    if isinstance(field_values, string_types):
        field_values = [field_values]

    if len(fields_names) != len(field_values):
        raise ValueError('Error: unable to build a primary key query due '
                         'to mismatch in number of fields {0} vs {1}'
                         .format(len(fields_names), len(field_values)))

    query = dict()
    for k, v in zip(fields_names, field_values):
        query[k] = v
    return query
317945
def parse_querystring(self, req, name, field):
        """"""
        return core.get_value(req.query, name, field)
1132955
def query(self, *q):
    
    params = join_params(self.parameters, {"q": q})

    return self.__class__(**params)
341577
def create_q(token):
    
    meta = getattr(token, 'meta', None)
    query = getattr(token, 'query', '')
    wildcards = None

    if isinstance(query, six.string_types):  # Unicode -> Quoted string
        search = query
    else:  # List -> No quoted string (possible wildcards)
        if len(query) == 1:
            search = query[0]
        elif len(query) == 3:
            wildcards = 'BOTH'
            search = query[1]
        elif len(query) == 2:
            if query[0] == '*':
                wildcards = 'START'
                search = query[1]
            else:
                wildcards = 'END'
                search = query[0]

    # Ignore short term and stop words
    if (len(search) < 3 and not search.isdigit()) or search in STOP_WORDS:
        return Q()

    if not meta:
        q = Q()
        for field in SEARCH_FIELDS:
            q |= Q(**{'%s__icontains' % field: search})
        return q

    if meta == 'category':
        if wildcards == 'BOTH':
            return (Q(categories__title__icontains=search) |
                    Q(categories__slug__icontains=search))
        elif wildcards == 'START':
            return (Q(categories__title__iendswith=search) |
                    Q(categories__slug__iendswith=search))
        elif wildcards == 'END':
            return (Q(categories__title__istartswith=search) |
                    Q(categories__slug__istartswith=search))
        else:
            return (Q(categories__title__iexact=search) |
                    Q(categories__slug__iexact=search))
    elif meta == 'author':
        if wildcards == 'BOTH':
            return Q(**{'authors__%s__icontains' % Author.USERNAME_FIELD:
                        search})
        elif wildcards == 'START':
            return Q(**{'authors__%s__iendswith' % Author.USERNAME_FIELD:
                        search})
        elif wildcards == 'END':
            return Q(**{'authors__%s__istartswith' % Author.USERNAME_FIELD:
                        search})
        else:
            return Q(**{'authors__%s__iexact' % Author.USERNAME_FIELD:
                        search})
    elif meta == 'tag':  # TODO: tags ignore wildcards
        return Q(tags__icontains=search)
959826
def build_query_string(self, data):
        
        query = []
        keys_to_be_removed = []
        for key, value in data.items():
            if key not in ['version', 'restApi', 'resourcePath']:
                if not key == 'method':
                    if key == 'points':
                        value = ','.join(str(val) for val in value)
                        keys_to_be_removed.append(key)
                    query.append('{0}={1}'.format(key, value))
                    keys_to_be_removed.append(key)
                keys_to_be_removed.append(key)
        querystring = '&'.join(query)
        data['query'] = '{0}?{1}'.format(data['method'], querystring)
        for k in list(set(keys_to_be_removed)):
            del data[k]
        return data
583511
def get_query(query_string, search_fields):
    
    query = None # Query to search for every search term        
    terms = normalize_query(query_string)
    for term in terms:
        or_query = None # Query to search for a given term in each field
        for field in search_fields:
            q = Q(**{"%s__%s" % (field[0], field[1]): term})
            if or_query is None:
                or_query = q
            else:
                or_query = or_query | q
        if query is None:
            query = or_query
        else:
            query = query & or_query
    return query
390597
def qs_from_dict(qsdict, prefix=""):
    ''' 
    '''
    prefix = prefix + '.' if prefix else ""

    def descend(qsd):
        for key, val in sorted(qsd.items()):
            if val:
                yield qs_from_dict(val, prefix + key)
            else:
                yield prefix + key
    return ",".join(descend(qsdict))
23999
def extract_queries(self, args, kwargs):
        '''
        
        '''
        # Please note the function signature is NOT an error.  Neither args, nor
        # kwargs should have asterisks.  We are passing in a list and dict,
        # rather than receiving variable args.  Adding asterisks WILL BREAK the
        # function completely.

        # First, this is the query buffer.  Contains lists of [base,sql]
        qbuffer = []

        # Add on the non-keywords...
        qbuffer.extend([[None, s] for s in args])

        # And then the keywords...
        # They aren't in definition order, but they can't conflict each other.
        klist = list(kwargs.keys())
        klist.sort()
        qbuffer.extend([[k, kwargs[k]] for k in klist])

        # Filter out values that don't have queries.
        qbuffer = [x for x in qbuffer if (
                (isinstance(x[1], six.string_types) and len(x[1]))
                or
                (isinstance(x[1], (list, tuple)) and (len(x[1]) > 0) and x[1][0])
                or
                (isinstance(x[1], dict) and 'query' in x[1] and len(x[1]['query']))
            )]

        # Next, turn the whole buffer into full dicts.
        for qb in qbuffer:
            defaults = {'query': '',
                        'depth': 0,
                        'as_list': False,
                        'with_lists': None,
                        'ignore_null': False
                        }
            if isinstance(qb[1], six.string_types):
                defaults['query'] = qb[1]
            elif isinstance(qb[1], (list, tuple)):
                defaults['query'] = qb[1][0]
                if len(qb[1]) > 1:
                    defaults['depth'] = qb[1][1]
                # May set 'as_list' from qb[1][2].
            else:
                defaults.update(qb[1])
                if defaults['with_lists'] and isinstance(defaults['with_lists'], six.string_types):
                    defaults['with_lists'] = [
                        int(i) for i in defaults['with_lists'].split(',')
                    ]
            qb[1] = defaults

        return qbuffer
430835
def f(field: str, kwargs: Dict[str, Any],
      default: Optional[Any] = None) -> str:
    
    if default is not None:
        return str(kwargs.get(field, default))
    return str(kwargs[field])
88532
def add_params_to_qs(query, params):
    """"""
    if isinstance(params, dict):
        params = params.items()
    queryparams = urlparse.parse_qsl(query, keep_blank_values=True)
    queryparams.extend(params)
    return urlencode(queryparams)
679742
def _parse_prefix_query(self, query_str):
        
        sp = smart_parsing.PrefixSmartParser()
        query = sp.parse(query_str)
        return query