use this if your are searching for a field in the same model
436315
def get_model_queries(self, query_obj, model_queries_config):
        """"""
        for search4, model_attrib in model_queries_config:

            if search4 is not None:
                query_obj = self._model_query(query_obj, search4, model_attrib)
        return query_obj
346818
function(query, model, logger) {
    const Log = logger.bind()
    if (query.$term) {
      query.$or = [] // TODO: allow option to choose ANDing or ORing of searchFields/queryableFields
      let queryableFields = this.getQueryableFields(model, Log)
      let stringFields = this.getStringFields(model, Log)

      // EXPL: we can only search fields that are a string type
      queryableFields = queryableFields.filter(function(field) {
        return stringFields.indexOf(field) > -1
      })

      // EXPL: search only specified fields if included
      if (query.$searchFields) {
        if (!Array.isArray(query.$searchFields)) {
          query.$searchFields = query.$searchFields.split(',')
        }

        // EXPL: we can only search fields that are a string type
        query.$searchFields = query.$searchFields.filter(function(field) {
          return stringFields.indexOf(field) > -1
        })

        query.$searchFields.forEach(function(field) {
          let obj = {}
          obj[field] = new RegExp(query.$term, 'i')
          query.$or.push(obj)
        })
      } else {
        queryableFields.forEach(function(field) {
          let obj = {}
          obj[field] = new RegExp(query.$term, 'i')
          query.$or.push(obj)
        })
      }
    }

    delete query.$searchFields
    delete query.$term
  }
1111124
def Many2ManyThroughModel(field):
    ''''''
    from stdnet.odm import ModelType, StdModel, ForeignKey, CompositeIdField
    name_model = field.model._meta.name
    name_relmodel = field.relmodel._meta.name
    # The two models are the same.
    if name_model == name_relmodel:
        name_relmodel += '2'
    through = field.through
    # Create the through model
    if through is None:
        name = '{0}_{1}'.format(name_model, name_relmodel)

        class Meta:
            app_label = field.model._meta.app_label
        through = ModelType(name, (StdModel,), {'Meta': Meta})
        field.through = through
    # The first field
    field1 = ForeignKey(field.model,
                        related_name=field.name,
                        related_manager_class=makeMany2ManyRelatedManager(
                            field.relmodel,
                            name_model,
                            name_relmodel)
                        )
    field1.register_with_model(name_model, through)
    # The second field
    field2 = ForeignKey(field.relmodel,
                        related_name=field.related_name,
                        related_manager_class=makeMany2ManyRelatedManager(
                            field.model,
                            name_relmodel,
                            name_model)
                        )
    field2.register_with_model(name_relmodel, through)
    pk = CompositeIdField(name_model, name_relmodel)
    pk.register_with_model('id', through)
107384
def find_by_field(self, table, field, field_value):
        '''
        
        '''
        sql = "select * from {} where {} = '{}'".format(
            table, field, field_value)
        res = self.query(sql)
        return res
1223297
def hasField(cls, fieldName) :
        """"""
        path = fieldName.split(".")
        v = cls._fields
        for k in path :
            try :
                v = v[k]
            except KeyError :
                return False
        return True
225415
def Where(self, field):
    
    where_builder = _WhereBuilder(self, field)
    self.where_builders.append(where_builder)
    return where_builder
196276
def match_fields(fields, searches,
                 ignore_case=False, wholename=False, complement=False):
    
    if ignore_case:
        fields = [f.lower() for f in fields]
        searches = [s.lower() for s in searches]
    if wholename:
        match_found = _complete_match
    else:
        match_found = _partial_match

    fields = [(i, field) for i, field in enumerate(fields)]
    matched = []
    for search, (idx, field) in itertools.product(searches, fields):
        if not search:  ## don't return all fields for ''
            continue
        if match_found(search, field) and idx not in matched:
            matched.append(idx)

    if complement:
        matched = [idx for idx in list(zip(*fields))[0] if idx not in matched]

    return matched
1136022
def get_field_type(field):
    
    if isinstance(field, core_filters.MappedMultipleChoiceFilter):
        return ' | '.join(['"%s"' % f for f in sorted(field.mapped_to_model)])
    if isinstance(field, OrderingFilter) or isinstance(field, ChoiceFilter):
        return ' | '.join(['"%s"' % f[0] for f in field.extra['choices']])
    if isinstance(field, ChoiceField):
        return ' | '.join(['"%s"' % f for f in sorted(field.choices)])
    if isinstance(field, HyperlinkedRelatedField):
        if field.view_name.endswith('detail'):
            return 'link to %s' % reverse(field.view_name,
                                          kwargs={'%s' % field.lookup_field: "'%s'" % field.lookup_field})
        return reverse(field.view_name)
    if isinstance(field, structure_filters.ServiceTypeFilter):
        return ' | '.join(['"%s"' % f for f in SupportedServices.get_filter_mapping().keys()])
    if isinstance(field, ResourceTypeFilter):
        return ' | '.join(['"%s"' % f for f in SupportedServices.get_resource_models().keys()])
    if isinstance(field, core_serializers.GenericRelatedField):
        links = []
        for model in field.related_models:
            detail_view_name = core_utils.get_detail_view_name(model)
            for f in field.lookup_fields:
                try:
                    link = reverse(detail_view_name, kwargs={'%s' % f: "'%s'" % f})
                except NoReverseMatch:
                    pass
                else:
                    links.append(link)
                    break
        path = ', '.join(links)
        if path:
            return 'link to any: %s' % path
    if isinstance(field, core_filters.ContentTypeFilter):
        return "string in form 'app_label'.'model_name'"
    if isinstance(field, ModelMultipleChoiceFilter):
        return get_field_type(field.field)
    if isinstance(field, ListSerializer):
        return 'list of [%s]' % get_field_type(field.child)
    if isinstance(field, ManyRelatedField):
        return 'list of [%s]' % get_field_type(field.child_relation)
    if isinstance(field, ModelField):
        return get_field_type(field.model_field)

    name = field.__class__.__name__
    for w in ('Filter', 'Field', 'Serializer'):
        name = name.replace(w, '')
    return FIELDS.get(name, name)
963137
def where_in(self, field_name, values, exact=False):
        
        field_name = Query.escape_if_needed(field_name)
        self._add_operator_if_needed()
        self.negate_if_needed(field_name)

        token = _Token(field_name=field_name, value=self.add_query_parameter(list(Utils.unpack_iterable(values))),
                       token="in", exact=exact)
        token.write = self.rql_where_write(token)
        self._where_tokens.append(token)

        return self
154780
def before_add_field(self, field):
        
        if self.extract_fields and field.name == '*':
            field.ignore = True
            fields = [model_field.column for model_field in self.model._meta.fields]
            self.add_fields(fields)
1289385
def _search(self, model, condition=None, search_field='name',
                value_field='id', label_field=None, pagination=True):
        
        from uliweb import json, request

        name = request.GET.get('term', '')
        M = functions.get_model(model)

        def _v(label_field):
            if label_field:
                return lambda x: getattr(x, label_field)
            else:
                return lambda x: unicode(x)

        v_field = request.values.get('label', 'title')
        page = int(request.values.get('page') or 1)
        limit = int(request.values.get('limit') or 10)
        v_func = _v(label_field)
        if name:
            if condition is None:
                condition = M.c[search_field].like('%' + name + '%')
            if pagination:
                query = M.filter(condition)
                total = query.count()
                rows = [{'id': getattr(obj, value_field), v_field: v_func(obj)}
                            for obj in query.limit(limit).offset((page-1)*limit)]
                result = {'total':total, 'rows':rows}
            else:
                result = [{'id': getattr(obj, value_field), v_field: v_func(obj)}
                      for obj in M.filter(condition)]
        else:
            result = []
        return json(result)
1254891
def get_fields(model, fields, meta=None):
    
    model = get_model(model)
    if fields is not None:
        f = fields
    elif meta and hasattr(model, meta):
        m = getattr(model, meta)
        if hasattr(m, 'fields'):
            f = m.fields
        else:
            f = model._fields_list
    else:
        f = model._fields_list
        
    fields_list = []
    for x in f:
        field = {}
        if isinstance(x, str):  #so x is field_name
            field['name'] = x
        elif isinstance(x, tuple):
            field['name'] = x[0]
            field['field'] = x[1]
        elif isinstance(x, dict):
            field = x.copy()
        else:
            raise UliwebError('Field definition {!r} is not right, it should be just like (field_name, form_field_obj)'.format(x))
        
        if 'prop' not in field:
            if hasattr(model, field['name']):
                field['prop'] = getattr(model, field['name'])
            else:
                field['prop'] = None
        
        fields_list.append((field['name'], field))
    return fields_list
743420
function(model) {
    var fields = _.keys(model);
    var updated = {};

    _.each(fields, function(field) {
        var updatedField = {};
        var modelField = {};
        if (!(field === Object(field))) {
            updatedField.field = field;
            if (!(model[field] === Object(model[field]))) {
                modelField = { type: model[field] };
            } else {
                modelField = model[field];
            }
            updatedField = _.defaults(updatedField, modelField);
        } else {
            updatedField = field;
        }
        updated[updatedField.field] = updatedField;
    });

    return updated;
}
335247
private static Field findField(Object object, FieldMatcherStrategy strategy, Class<?> where) {
        return findSingleFieldUsingStrategy(strategy, object, false, where);
    }
304251
def get_real_field(model, field_name):
    '''
    
    '''
    parts = field_name.split('__')
    field = model._meta.get_field(parts[0])
    if len(parts) == 1:
        return model._meta.get_field(field_name)
    elif isinstance(field, models.ForeignKey):
        return get_real_field(field.rel.to, '__'.join(parts[1:]))
    else:
        raise Exception('Unhandled field: %s' % field_name)
387452
def search(self, *args, **kwargs):
        
        if not settings.SEARCH_MODEL_CHOICES:
            # No choices defined - build a list of leaf models (those
            # without subclasses) that inherit from Displayable.
            models = [m for m in apps.get_models()
                      if issubclass(m, self.model)]
            parents = reduce(ior, [set(m._meta.get_parent_list())
                                   for m in models])
            models = [m for m in models if m not in parents]
        elif getattr(self.model._meta, "abstract", False):
            # When we're combining model subclasses for an abstract
            # model (eg Displayable), we only want to use models that
            # are represented by the ``SEARCH_MODEL_CHOICES`` setting.
            # Now this setting won't contain an exact list of models
            # we should use, since it can define superclass models such
            # as ``Page``, so we check the parent class list of each
            # model when determining whether a model falls within the
            # ``SEARCH_MODEL_CHOICES`` setting.
            search_choices = set()
            models = set()
            parents = set()
            errors = []
            for name in settings.SEARCH_MODEL_CHOICES:
                try:
                    model = apps.get_model(*name.split(".", 1))
                except LookupError:
                    errors.append(name)
                else:
                    search_choices.add(model)
            if errors:
                raise ImproperlyConfigured("Could not load the model(s) "
                        "%s defined in the 'SEARCH_MODEL_CHOICES' setting."
                        % ", ".join(errors))

            for model in apps.get_models():
                # Model is actually a subclasses of what we're
                # searching (eg Displayabale)
                is_subclass = issubclass(model, self.model)
                # Model satisfies the search choices list - either
                # there are no search choices, model is directly in
                # search choices, or its parent is.
                this_parents = set(model._meta.get_parent_list())
                in_choices = not search_choices or model in search_choices
                in_choices = in_choices or this_parents & search_choices
                if is_subclass and (in_choices or not search_choices):
                    # Add to models we'll seach. Also maintain a parent
                    # set, used below for further refinement of models
                    # list to search.
                    models.add(model)
                    parents.update(this_parents)
            # Strip out any models that are superclasses of models,
            # specifically the Page model which will generally be the
            # superclass for all custom content types, since if we
            # query the Page model as well, we will get duplicate
            # results.
            models -= parents
        else:
            models = [self.model]
        all_results = []
        user = kwargs.pop("for_user", None)
        for model in models:
            try:
                queryset = model.objects.published(for_user=user)
            except AttributeError:
                queryset = model.objects.get_queryset()
            all_results.extend(queryset.search(*args, **kwargs))
        return sorted(all_results, key=lambda r: r.result_count, reverse=True)
1247114
def one_line_filter

      if (attributes.keys - COMMON_ATT_KEYS - %w[ ref original_ref ]).empty?
        return nil
      end

      [ attributes.remap { |(k, v), h|
        if v.nil?
          h['field'] = k
        else
          h[k] = v
        end
      } ]
    end