Attach default fields and meta options to models
974383
def process_models(attrs, base_model_class):
        
        attrs.update(base_model_class._DEFAULT_BASE_FIELDS)
        attrs['_instance_registry'] = set()
        attrs['_is_unpermitted_fields_set'] = False
        attrs['save_meta_data'] = None
        attrs['_pre_save_hook_called'] = False
        attrs['_post_save_hook_called'] = False
        DEFAULT_META = {'bucket_type': settings.DEFAULT_BUCKET_TYPE,
                        'field_permissions': {},
                        'app': 'main',
                        'list_fields': [],
                        'list_filters': [],
                        'search_fields': [],
                        'fake_model': False,
                        }
        if 'Meta' not in attrs:
            attrs['Meta'] = type('Meta', (object,), DEFAULT_META)
        else:
            for k, v in DEFAULT_META.items():
                if k not in attrs['Meta'].__dict__:
                    setattr(attrs['Meta'], k, v)
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
602302
protected function setupDefaultOptions()
    {
        $defaults = [
            'overwriteInitial'     => false,
            'initialPreviewAsData' => true,
            'browseLabel'          => trans('admin.browse'),
            'cancelLabel'          => trans('admin.cancel'),
            'showRemove'           => false,
            'showUpload'           => false,
            'dropZoneEnabled'      => false,
            'deleteExtraData'      => [
                $this->formatName($this->column) => static::FILE_DELETE_FLAG,
                static::FILE_DELETE_FLAG         => '',
                '_token'                         => csrf_token(),
                '_method'                        => 'PUT',
            ],
        ];

        if ($this->form instanceof Form) {
            $defaults['deleteUrl'] = $this->form->resource().'/'.$this->form->model()->getKey();
        }

        $defaults = array_merge($defaults, ['fileActionSettings' => $this->fileActionSettings]);

        $this->options($defaults);
    }
1015611
private function defaultFields()
    {
        $owner = $this->owner;
        $this->field_list = array(
            'Root.Main' => array(
                0  => TextField::create('Title', $owner->fieldLabel('Title')),
                6  => HTMLEditorField::create('Content', $owner->fieldLabel('Content')),
                8  => TextField::create('Author', $owner->fieldLabel('Author')),
                9  => DateField::create('PublishFrom', $owner->fieldLabel('PublishFrom'))->setConfig('showcalendar', true),
                10 => CheckboxField::create('Live', $owner->fieldLabel('Published')),
                11 => CheckboxField::create('Commenting', $owner->fieldLabel('Commenting')),
                12 => UploadField::create('Impression', $owner->fieldLabel('Impression')),
            )
        );
        $this->field_list['Root.Main'][9]->setConfig('dateformat', 'yyyy-MM-dd');
    }
198752
private static void populateEmbeddedIdFields(Set<Attribute> embeddedAttributes, MetamodelImpl metaModel,
            Set<String> embeddedIdFields)
    {
        for (Attribute attribute : embeddedAttributes)
        {
            if (!ReflectUtils.isTransientOrStatic((Field) attribute.getJavaMember()))
            {
                if (metaModel.isEmbeddable(attribute.getJavaType()))
                {
                    EmbeddableType embeddable = metaModel.embeddable(attribute.getJavaType());
                    populateEmbeddedIdFieldsUtil(embeddable.getAttributes(), metaModel, embeddedIdFields);
                }
            }
        }
    }
318904
def generate_form(model, only=None, meta=None):
    
    fields = OrderedDict()
    if meta:
        fields['Meta'] = meta

    for name, column in model.__dict__['columns'].items():
        if only:
            if not name in only:
                continue
        if not isinstance(column, Column):
            continue
        fields[name] = TYPE_MAP[column.type.__class__](
            name, render_kw={'placeholder': name}
        )
    form = type(
        'Add{}Form'.format(model.name.capitalize()),
        (Form,),
        fields
    )
    return form
76324
def _fill_auto_fields(model, values):
    
    auto_field_names = [
        f.attname
        for f in model._meta.fields
        if getattr(f, 'auto_now', False) or getattr(f, 'auto_now_add', False)
    ]
    now = timezone.now()
    for value in values:
        for f in auto_field_names:
            setattr(value, f, now)

    return values
1348538
def _get_model_fields(self, field_names, declared_fields, extra_kwargs):
        
        model = getattr(self.Meta, 'model')
        model_fields = {}

        for field_name in field_names:
            if field_name in declared_fields:
                # If the field is declared on the serializer
                field = declared_fields[field_name]
                source = field.source or field_name
            else:
                try:
                    source = extra_kwargs[field_name]['source']
                except KeyError:
                    source = field_name

            if '.' in source or source == '*':
                # Model fields will always have a simple source mapping,
                # they can't be nested attribute lookups.
                continue

            try:
                field = model._meta.get_field(source)
                if isinstance(field, DjangoModelField):
                    model_fields[source] = field
            except FieldDoesNotExist:
                pass

        return model_fields
882613
def model_fields(model, db_session=None, only=None, exclude=None,
                 field_args=None, converter=None, exclude_pk=False,
                 exclude_fk=False):
    
    mapper = model._sa_class_manager.mapper
    converter = converter or _ModelConverter()
    field_args = field_args or {}
    properties = []

    for prop in mapper.iterate_properties:
        if getattr(prop, 'columns', None):
            if exclude_fk and prop.columns[0].foreign_keys:
                continue
            elif exclude_pk and prop.columns[0].primary_key:
                continue

        properties.append((prop.key, prop))

    # the following if condition is modified:
    if only is not None:
        properties = (x for x in properties if x[0] in only)
    elif exclude:
        properties = (x for x in properties if x[0] not in exclude)

    field_dict = {}
    for name, prop in properties:
        field = converter.convert(
            model, mapper, prop,
            field_args.get(name), db_session
        )
        if field is not None:
            field_dict[name] = field

    return field_dict
676455
def build_dynamic_field(self, group, field_meta):
        
        schema = field_meta['schema']

        # set up some defaults for form fields
        fieldtype = 'text'
        fkwargs = {
            'label': field_meta['name'],
            'required': field_meta['required'],
        }
        # override defaults based on field configuration
        if (schema['type'] in ['securitylevel', 'priority']
                or schema.get('custom') == JIRA_CUSTOM_FIELD_TYPES['select']):
            fieldtype = 'select'
            fkwargs['choices'] = self.make_choices(field_meta.get('allowedValues'))
        elif field_meta.get('autoCompleteUrl') and \
                (schema.get('items') == 'user' or schema['type'] == 'user'):
            fieldtype = 'select'
            sentry_url = '/api/0/issues/%s/plugins/%s/autocomplete' % (group.id, self.slug)
            fkwargs['url'] = '%s?jira_url=%s' % (
                sentry_url, quote_plus(field_meta['autoCompleteUrl']),
            )
            fkwargs['has_autocomplete'] = True
            fkwargs['placeholder'] = 'Start typing to search for a user'
        elif schema['type'] in ['timetracking']:
            # TODO: Implement timetracking (currently unsupported alltogether)
            return None
        elif schema.get('items') in ['worklog', 'attachment']:
            # TODO: Implement worklogs and attachments someday
            return None
        elif schema['type'] == 'array' and schema['items'] != 'string':
            fieldtype = 'select'
            fkwargs.update(
                {
                    'multiple': True,
                    'choices': self.make_choices(field_meta.get('allowedValues')),
                    'default': []
                }
            )

        # break this out, since multiple field types could additionally
        # be configured to use a custom property instead of a default.
        if schema.get('custom'):
            if schema['custom'] == JIRA_CUSTOM_FIELD_TYPES['textarea']:
                fieldtype = 'textarea'

        fkwargs['type'] = fieldtype
        return fkwargs
1143316
def get_model_fields(self):
        

        model_fields = getattr(self.Meta, 'fields', None)

        if model_fields is not None:
            model_fields = set(model_fields)

        return model_fields
50712
function replaceVirtualFields(options, model) {
		if (options.attributes) {
			for (var i = 0; i < options.attributes.length; i++) { // not using _.forEach as array is altered during looping
				var fieldName = options.attributes[i],
					field = model.attributes[fieldName];

				if (!field) throw new Sequelize.VirtualFieldsError("Field '" + model.name + '.' + fieldName + "' referenced in a virtual field does not exist");

				if (!(field.type instanceof Sequelize.VIRTUAL)) continue;

				// field is virtual - add attributes & includes from virtualField
				addVirtualFieldOptions(options, field, fieldName);

				// delete virtual attribute
				options.attributes.splice(i, 1);
				i--;
			}
		} else {
			// no attributes specified - all attributes of model will load so check all virtualFields
			_.forIn(model.attributes, function(field, fieldName) {
				// add attributes & includes from virtual field
				if (field.type instanceof Sequelize.VIRTUAL) addVirtualFieldOptions(options, field, fieldName);
			});
		}

		// repeat process for all includes recursively
		var includes = options.include;
		if (includes) {
			_.forEach(includes, function(include, index) {
				// if include given as model with no attributes/include, convert to {model: model} notation
				if (patches.isModel(include)) include = includes[index] = {model: include};

				// recurse through this include
				replaceVirtualFields(include, include.model);
			});
		}
	}
154264
function buildFields (model, fields) {
    //  build list of fields from columns and properties properties
    if (!fields) {
        fields = _.keys(model.extraColumns)
        // if model has schema and properties
        if (model.schemaData) {
            fields = _.uniq( fields.concat( _.keys(model.schemaData.properties) ) )
        }
        // add create time field
        fields.push(metaFields.createTime)
        // add actions field
        fields.push(metaFields.actions)
    }
    // process fields
    fields = _.map(fields, field => {
        // if field is a string the build object
        if (typeof field === 'string') {
            // if field is a meta column then add spec
            if (metaFields[field]) {
                return metaFields[field]
            }
            // create spec
            else {
                field = {
                    property: field,
                }
            }
        }
        // create default label if label not set
        if (!field.title) {
            // use property name converted to upper case first words
            field.title = changeCase.titleCase(field.property)
        }
        // get column for property (if any)
        var column = model.columns[field.property]
        // if field is column then set properties based on column
        if (column) {
            // if column has index allow filter and search on column
            if (column.index || column.unique) {
                field.orderAscIcon = 'sort-alpha-asc'
                field.orderAscUrl = './?orderColumn='+field.property+'&orderDirection=ASC'
                field.orderDescIcon = 'sort-alpha-desc'
                field.orderDescUrl = './?orderColumn='+field.property+'&orderDirection=DESC'
                field.searchBy = true
                field.searchIcon =  'search'
            }
        }
        // return field spec
        return field
    })
    // return formatted fields
    return fields
}
410513
def _attach_to_model(self, model):
        
        super(RelatedFieldMixin, self)._attach_to_model(model)

        if model.abstract:
            # do not manage the relation if it's an abstract model
            return

        # now, check related_name and save the relation in the database

        # get related parameters to identify the relation
        self.related_name = self._get_related_name()
        self.related_to = self._get_related_model_name()

        # create entry for the model in the _relations list of the database
        if not hasattr(self.database, '_relations'):
            self.database._relations = {}
        self.database._relations.setdefault(self.related_to, [])

        # check unicity of related name for related model
        self._assert_relation_does_not_exists()

        # the relation didn't exists, we can save it
        relation = (self._model._name, self.name, self.related_name)
        self.database._relations[self.related_to].append(relation)
1358383
def add_columns(self, model, **fields):
        """"""
        for name, field in fields.items():
            model._meta.add_field(name, field)
            self.ops.append(self.migrator.add_column(
                model._meta.table_name, field.column_name, field))
            if field.unique:
                self.ops.append(self.migrator.add_index(
                    model._meta.table_name, (field.column_name,), unique=True))
        return model
660425
protected function setDefaultFieldDefinitions() : void
    {
        $table = $this->config->getTable();
        $field = $this->config->getField();
        $dbFieldType = $this->getDbFieldType();

        // set $options['fieldDefinitions']
        $stubFields = [
            $field => [
                'name' => $field,
                'type' => $dbFieldType,
            ],
        ];
        if ($table instanceof HasFieldsInterface) {
            $fieldDefinitions = $table->getFieldsDefinitions($stubFields);
            $this->defaultOptions['fieldDefinitions'] = new CsvField($fieldDefinitions[$field]);
        }

        // This should never be the case, except, maybe
        // for some unit test runs or custom non-CSV
        // modules.
        if (empty($this->defaultOptions['fieldDefinitions'])) {
            $this->defaultOptions['fieldDefinitions'] = new CsvField($stubFields[$field]);
        }
    }
407961
def augment_model_meta(model, db_alias, model_meta, column_name_filters=None, count=0, verbosity=0):
    """"""
    if settings.DEBUG and verbosity > 2:
        print 'Augmenting model meta data for %r...' % model

    column_name_filters = util.listify(column_name_filters)
    queryset = djdb.get_queryset(model)

    if db_alias:
        queryset = queryset.using(db_alias)
    for field_name in model._meta.get_all_field_names():
        field = None
        try:
            field = model._meta.get_field(field_name)
            db_column = field.db_column
        # Django creates reverse ForeignKey relationship fields that may not have a database column in this table
        # This happens if you make existing fields/columns in other tables a ForeignKey referencing this table
        except FieldDoesNotExist:
            db_column = None
        if not field:
            if verbosity > 0:
                print "WARNING: Skipped 'phantom' field named '%s'.  This is likely because of a ForeignKey relationship elsewhere back to this model (%r). No field found in the model '%s' for database '%s'." % (field_name, model, model.__name__, db_alias)
            continue
        if not db_column:
            if field.name in model_meta:
                db_column = field.name
            elif field.name.lower() in model_meta:
                db_column = field.name.lower()
            elif field.name.upper() in model_meta:
                db_column = field.name.upper()
        if not db_column:
            if verbosity > 0:
                print "WARNING: Skipped field named '%s'. No column found in the database.table '%s.%s'." % (field.name, db_alias, model.__name__)
            continue
        if column_name_filters:
            if not any(((callable(cnf) and cnf(db_column)) or (db_column == cnf)) for cnf in column_name_filters):
                if verbosity > 0:
                    print "WARNING: Skipped field named '%s' for table '%s.%s' because it didn't match any filters: %r." % (field.name, db_alias, model.__name__, column_name_filters)
                continue
        if (field.name == 'id' and isinstance(field, models.fields.AutoField)
                and field.primary_key and (not model_meta[db_column]['primary_key'])):
            print "WARNING: Skipped field named '%s' for table '%s.%s' because it is an AutoField and no primary_key is defined for this table." % (field.name, db_alias, model.__name__)
            continue

        model_meta[db_column] = augment_field_meta(field, queryset, model_meta[db_column], count=count, verbosity=verbosity)
        if verbosity > 1:
            print '%s (%s of type %s) has %s / %s (%3.1f%%) distinct values between %s and %s, excluding %s nulls.' % (field.name, db_column, 
                                                        model_meta[db_column]['type'],
                                                        model_meta[db_column]['num_distinct'], 
                                                        count,
                                                        100. * (model_meta[db_column]['num_distinct'] or 0) / (count or 1),
                                                        repr(model_meta[db_column]['min']),
                                                        repr(model_meta[db_column]['max']),
                                                        model_meta[db_column]['num_null'])
    return model_meta