Fix fieldname for ForeignKeys.
172331
def alter_add_column(self, table, column_name, field, **kwargs):
        """"""
        name = field.name
        op = super(SchemaMigrator, self).alter_add_column(table, column_name, field, **kwargs)
        if isinstance(field, pw.ForeignKeyField):
            field.name = name
        return op
738879
def _fieldnames_to_colnames(model_cls, fieldnames):
        """"""
        get_field = model_cls._meta.get_field
        fields = map(get_field, fieldnames)
        return {f.column for f in fields}
1050904
def convert_pk_field_names_to_real(model, field_names):
    
    pk_field_names = tuple(f.name for f in model._get_primary_key_columns())

    def append_field(field_name):
        if field_name not in real_field_names:
            real_field_names.append(field_name)

    real_field_names = []
    for name in field_names:
        if name == 'pk':
            for real_pk_field_name in pk_field_names:
                append_field(real_pk_field_name)
        elif name == '-pk':
            for real_pk_field_name in pk_field_names:
                append_field('-' + real_pk_field_name)
        else:
            append_field(name)
    return real_field_names
1251526
def set_foreign_key(self, parent_table, parent_column, child_table, child_column):
        """"""
        self.execute('ALTER TABLE {0} ADD FOREIGN KEY ({1}) REFERENCES {2}({3})'.format(parent_table, parent_column,
                                                                                        child_table, child_column))
1228154
public String foreignKeyColumnName(
			String propertyName, String propertyEntityName, String propertyTableName, String referencedColumnName
	) {
		String header = propertyName != null ? unqualify( propertyName ) : propertyTableName;
		
		checkState(header != null, "NamingStrategy not properly filled");
		
		return columnName( header ); //+ "_" + referencedColumnName not used for backward compatibility
	}
911373
function getBelongsToName(fkc) {
    var as          = fkc.foreignKey(0).name(),                                             // company_id
        tableName   = fkc.table().name(),
        camelCase   = getSpecificConfig(tableName, 'generate.relationAccessorCamelCase'),
        prefix      = getSpecificConfig(tableName, 'generate.prefixForBelongsTo');          // related

    if (as.match(/_id$/i)) {
        as = as.replace(/_id$/i, '');                                                       // company_id -> company
    } else {
        as = prefix + '_' + as;                                                             // company -> related_company
    }
    if (camelCase) {
        as = inflection.camelize(inflection.underscore(as), true);
    }
    return inflection.singularize(as);
}
1126416
def columns(self):
        """"""
        res = [col['name'] for col in self.column_definitions]
        res.extend([col['name'] for col in self.foreign_key_definitions])
        return res
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
527718
def get_localized_field_name(context, field):
    """"""
    attrs = [
             translation.get_language(), 
             translation.get_language()[:2], 
             settings.LANGUAGE_CODE
            ]
            
    def predicate(x):
        field_name = get_real_fieldname(field, x)
        if hasattr(context, field_name):
            return field_name
        return None

    return first_match(predicate, attrs)
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)
988945
def __fieldNorm(self, fieldName):
        """"""
        if len(fieldName) > 11: fieldName = fieldName[:11]
        fieldName = fieldName.upper()
        fieldName.replace(' ', '_')
320235
protected function buildForeignKeyName($foreignKey, $baseTable)
    {
        return (is_null($foreignKey)) ?
            Inflector::singularize($baseTable).self::DEFAULT_FOREIGN_KEY_SUFFIX :
            $foreignKey;
    }
244025
def filter(self, field_name, field_value):
        
        self.filters.append((field_name, field_value))
        return self
885131
def generic_find_fk_constraint_names(table, columns, referenced, insp):
    """"""
    names = set()

    for fk in insp.get_foreign_keys(table):
        if fk['referred_table'] == referenced and set(fk['referred_columns']) == columns:
            names.add(fk['name'])

    return names
656676
def patch_clean_fields(model):
    
    old_clean_fields = model.clean_fields

    def new_clean_fields(self, exclude=None):
        if hasattr(self, '_mt_form_pending_clear'):
            # Some form translation fields has been marked as clearing value.
            # Check if corresponding translated field was also saved (not excluded):
            # - if yes, it seems like form for MT-unaware app. Ignore clearing (left value from
            #   translated field unchanged), as if field was omitted from form
            # - if no, then proceed as normally: clear the field
            for field_name, value in self._mt_form_pending_clear.items():
                field = self._meta.get_field(field_name)
                orig_field_name = field.translated_field.name
                if orig_field_name in exclude:
                    field.save_form_data(self, value, check=False)
            delattr(self, '_mt_form_pending_clear')
        old_clean_fields(self, exclude)
    model.clean_fields = new_clean_fields
433479
def update_empty_fields(self, **kwargs):
        """"""
        if self._is_deprecated is None:
            self._is_deprecated = kwargs.get('is_deprecated')
        if self._is_dubious is None:
            self._is_dubious = kwargs.get('is_dubious')
        if self._is_synonym is None:
            self._is_synonym = kwargs.get('is_synonym')
        if self._synonyms is _EMPTY_TUPLE:
            self._synonyms = kwargs.get('synonyms')
            if self._synonyms is None:
                self._synonyms = _EMPTY_TUPLE
        if self.rank is None:
            self._rank = kwargs.get('rank')
        if self._nomenclature_code:
            self._nomenclature_code = kwargs.get('nomenclature_code')
        if not self._unique_name:
            self._unique_name = kwargs.get('unique_name')
        if self._taxonomic_lineage is None:
            self._taxonomic_lineage = kwargs.get('taxonomic_lineage')
        if self._parent is None:
            self._parent = kwargs.get('parent')
            if self._parent is None and self._taxomachine_wrapper is not None and self._taxonomic_lineage:
                self._fill_parent_attr()
416952
def bind_fields_to_model_cls(cls, model_fields):
        """"""
        return dict(
            (field.name, field.bind_model_cls(cls)) for field in model_fields)