Searches in the fields of the given related model and returns the
        result as a simple string to be used by the jQuery Autocomplete plugin
435630
def autocomplete_view(self, request):
        
        query = request.GET.get('q', None)
        app_label = request.GET.get('app_label', None)
        model_name = request.GET.get('model_name', None)
        search_fields = request.GET.get('search_fields', None)
        object_pk = request.GET.get('object_pk', None)

        try:
            to_string_function = self.related_string_functions[model_name]
        except KeyError:
            to_string_function = lambda x: str(x)

        if search_fields and app_label and model_name and (query or object_pk):

            def construct_search(field_name):
                # use different lookup methods depending on the notation
                if field_name.startswith('^'):
                    fmt, name = "{}__istartswith", field_name[1:]
                elif field_name.startswith('='):
                    fmt, name = "{}__iexact", field_name[1:]
                elif field_name.startswith('@'):
                    fmt, name = "{}__search", field_name[1:]
                else:
                    fmt, name = "{}__icontains", field_name
                return fmt.format(name)

            model = apps.get_model(app_label, model_name)
            queryset = model._default_manager.all()
            data = ''
            if query:
                for bit in query.split():
                    or_queries = [
                        models.Q(**{construct_search(smart_str(field_name)): smart_str(bit)})
                        for field_name
                        in search_fields.split(',')
                    ]
                    other_qs = QuerySet(model)
                    other_qs.query.select_related = queryset.query.select_related
                    other_qs = other_qs.filter(reduce(operator.or_, or_queries))
                    queryset = queryset & other_qs

                if self.autocomplete_limit:
                    queryset = queryset[:self.autocomplete_limit]

                data = ''.join([
                    '{}|{}\n'.format(to_string_function(f), f.pk)
                    for f
                    in queryset
                ])
            elif object_pk:
                try:
                    obj = queryset.get(pk=object_pk)
                except:
                    pass
                else:
                    data = to_string_function(obj)
            return HttpResponse(data)
        return HttpResponseNotFound()
1277536
protected function autocompletefield() {
		if ( ! $this->autocompleted) {
			$fieldname = $this->get('name', null);

			if ($fieldname !== null && ($autovalue = $this->form->autovalue($fieldname)) !== null) {
				$this->value_is($autovalue);
			}

			$this->autocompleted = true;
		}
	}
259289
function parseIncludes(field, fieldName, modelName, parent) {
		// check all attributes are strings and valid fields
		if (!field.attributes) {
			field.attributes = [];
		} else {
			if (!Array.isArray(field.attributes)) field.attributes = [field.attributes];

			_.forEach(field.attributes, function(attribute) {
				if (!_.isString(attribute)) throw new Sequelize.VirtualFieldsError("Attribute of virtual field '" + modelName + "'.'" + fieldName + "' is not a string");

				if (!parent.attributes[attribute]) throw new Sequelize.VirtualFieldsError("Attribute of virtual field '" + modelName + "'.'" + fieldName + "' refers to a nonexistent field '" + parent.name + "'.'" + attribute + "'");
			});
		}

		// format includes as {model: model, as: as} and convert strings to models
		if (field.include) {
			if (!Array.isArray(field.include)) field.include = [field.include];

			_.forEach(field.include, function(include, index) {
				include = parseClause(field.include, index, 'Include', modelName, fieldName, parent);

				parseIncludes(include, fieldName, modelName, include.model);
			});
		}
	}
1347596
function(instances) {
    var queryKey = this.foreignKey;
    var pks = _.map(instances, this.primaryKey);

    if (instances.length === 1) { pks = pks[0]; }
    else { queryKey += '$in'; }

    var where = _.object([[queryKey, pks]]);
    return this._relatedModel.objects.where(where);
  }
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
  }
1112459
def get_field(name, model=None):
    
    if '.' in name:
        m, name = name.split('.')
        model = get_model(m)

    if model:
        return getattr(model, name, None)
1136893
def query(self, model):
        '''
        '''
        session = self.router.session()
        fields = tuple((f.name for f in model._meta.scalarfields
                        if f.type == 'text'))
        qs = session.query(model).load_only(*fields)
        for related in self.get_related_fields(model):
            qs = qs.load_related(related)
        return qs
334241
function(params, callback) {
      var t = this;
      if (typeof(params) !== 'string' || params.length < 1) {
        callback("Autocomplete paramter must be a nonzero string");
      }

      // Forward to the completion mechanism if it can be completed
      if (params.substr(-1).match(/([0-9])|([a-z])|([A-Z])|([_])/)) {
        t.repl.complete(params, callback);
      } else {
        // Return a no-op autocomplete
        callback(null, [[],'']);
      }
    }
1374764
def get_related_fields(model_class, field_name, path=""):
    
    if field_name:
        field, model, direct, m2m = _get_field_by_name(model_class, field_name)
        if direct:
            # Direct field
            try:
                new_model = _get_remote_field(field).parent_model()
            except AttributeError:
                new_model = _get_remote_field(field).model
        else:
            # Indirect related field
            if hasattr(field, 'related_model'):  # Django>=1.8
                new_model = field.related_model
            else:
                new_model = field.model()

        path += field_name
        path += '__'
    else:
        new_model = model_class

    new_fields = get_relation_fields_from_model(new_model)
    model_ct = ContentType.objects.get_for_model(new_model)

    return (new_fields, model_ct, path)
1081689
def get_model_field(model, field_name):
    
    meta = model._meta
    try:
        if DJANGO19:
            field = meta.get_field(field_name)
        else:
            field = meta.get_field_by_name(field_name)[0]
        return field
    except:
        if DJANGO19:
            related_objs = (
                f for f in meta.get_fields()
                if (f.one_to_many or f.one_to_one)
                and f.auto_created and not f.concrete
            )
            related_m2m_objs = (
                f for f in meta.get_fields(include_hidden=True)
                if f.many_to_many and f.auto_created
            )
        else:
            related_objs = meta.get_all_related_objects()
            related_m2m_objs = meta.get_all_related_many_to_many_objects()

        related_objects = {
            o.get_accessor_name(): o
            for o in chain(related_objs, related_m2m_objs)
        }
        if field_name in related_objects:
            return related_objects[field_name]
        else:
            # check virtual fields (1.7)
            if hasattr(meta, 'virtual_fields'):
                for field in meta.virtual_fields:
                    if field.name == field_name:
                        return field

            raise AttributeError(
                '%s is not a valid field for %s' % (field_name, model)
            )
763322
public function afterFind()
    {
        /** @var ActiveRecord $owner */
        $owner = $this->owner;

        if ($owner->isRelationPopulated('translations') && $related = $owner->getRelatedRecords()['translations']) {
            $translations = $this->indexByLanguage($related);
            foreach ($this->_languageKeys as $language) {
                foreach ($this->attributes as $attribute) {
                    foreach ($translations as $translation) {
                        if ($translation->{$this->languageField} == $language) {
                            $attributeName = $this->localizedPrefix . $attribute;
                            $this->setMultilingualAttribute($this->getAttributeName($attribute, $language), $translation->{$attributeName});
                        }
                    }
                }
            }
        } else if ($owner->getAttribute($this->_ownerPrimaryKey) !== null) {
            if (!$owner->isRelationPopulated('translation')) {
                $owner->translation;
            }

            $translation = $owner->getRelatedRecords()['translation'];
            if ($translation) {
                foreach ($this->attributes as $attribute) {
                    $attribute_name = $this->localizedPrefix . $attribute;
                    $owner->setMultilingualAttribute($attribute, $translation->$attribute_name);
                }
            }
        }

        foreach ($this->attributes as $attribute) {
            if ($owner->hasAttribute($attribute) && $this->getMultilingualAttribute($attribute)) {
                $owner->setAttribute($attribute, $this->getMultilingualAttribute($attribute));
            }
        }
    }
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
1110618
function getFieldsForModelTemplate(fields) {
    var lg = fields.length - 1;

    var modelFields = '{' + os.EOL;
    fields.forEach(function(field, index, array) {
        modelFields += '\t\'' + field.name + '\' : '+ (field.isArray ? '[' : '') + (allowedFieldsTypes[field.type]).name + (field.isArray ? ']' : '');
        modelFields += (lg > index) ? ',' + os.EOL : os.EOL;

        if (field.reference) {
            modelFields = modelFields.replace(/{ref}/, field.reference);
        }
    });
    modelFields += '}';

    return modelFields;
}
536786
public function render()
    {
        // Always add this class
        $this->addClass('autocomplete');

        // Make the hidden field.  Render it before we (might) set the value to
        // the title of the parent.
        $hidden = $this->renderHidden();

        // If there is a value and the field name matches a relationship on function
        // on the current item, then get and display the title text for the related
        // record
        if ($parent = $this->parentModel()) {
            $this->value = $parent->getAdminTitleAttribute();

        // Else, if there is no parent (it's a create page), set the value if a
        // title was set
        } elseif ($this->title) {
            $this->value = $this->title;
        }

        // Add the hidden field and return
        return parent::render().$hidden;
    }
156068
def _expand_group_by_fields(cls, model, fields):
        
        # Containers for resulting fields and related model fields
        res = []
        related = {}

        # Add own fields and populate related fields
        for field_name in fields:
            if '__' in field_name:
                # Related model field: append to related model's fields
                fk_field_name, related_field = field_name.split('__', 1)
                if fk_field_name not in related:
                    related[fk_field_name] = [related_field]
                else:
                    related[fk_field_name].append(related_field)

            else:
                # Simple field, get the field instance
                model_field = model._meta.get_field(field_name)

                if isinstance(model_field, (ForeignKey, ManyToManyField)):
                    # It's a related field, get model
                    related_model = model_field.related_model

                    # Append all its fields with the correct prefix
                    res.extend('{}__{}'.format(field_name, f.column)
                               for f in related_model._meta.fields)

                else:
                    # It's a common field, just append it
                    res.append(field_name)

        # Resolve all related fields
        for fk_field_name, field_names in related.items():
            # Get field
            fk = model._meta.get_field(fk_field_name)

            # Get all fields for that related model
            related_fields = cls._expand_group_by_fields(fk.related_model,
                                                         field_names)

            # Append them with the correct prefix
            res.extend('{}__{}'.format(fk_field_name, f) for f in related_fields)

        # Return all fields
        return res
1222438
def get_field_model(name, model=None):
    
    if '.' in name:
        m, name = name.split('.')
        model = get_model(m)

    if model:
        return getattr(model, name, None), model
    else:
        return None, None
28020
function(query, model, logger) {
    // This line has to come first
    validationHelper.validateModel(model, logger)

    let attributesFilter = []
    let fields = model.schema.paths
    let fieldNames = []

    if (query.$select) {
      if (!Array.isArray(query.$select)) {
        query.$select = query.$select.split(',')
      }
      fieldNames = query.$select
    } else {
      fieldNames = Object.keys(fields)
    }

    let associations = model.routeOptions
      ? model.routeOptions.associations
      : null

    for (let i = 0; i < fieldNames.length; i++) {
      let fieldName = fieldNames[i]
      if (
        fields[fieldName] &&
        fieldName !== '__v' &&
        fieldName.substr(-2) !== '$*'
      ) {
        let field = fields[fieldName].options
        let association = associations
          ? associations[fields[fieldName].path] || {}
          : {}

        // EXPL: by default we don't include MANY_MANY array references
        if (
          !field.exclude &&
          (association.type !== 'MANY_MANY' || query.$select)
        ) {
          attributesFilter.push(fieldName)
        }
      }
    }

    delete query.$select
    return attributesFilter.toString().replace(/,/g, ' ')
  }