'Remove a Foreign Key constraint from a table'

def remove_foreign(self, tablename, fieldname):

    db = self.db
    db_engine = self.db_engine
    executesql = db.executesql
    if (tablename == 'all'):
        tables = db.tables
    else:
        tables = [tablename]
    for tablename in tables:
        if (fieldname not in db[tablename].fields):
            continue
        if (db_engine == 'sqlite'):
            raise NotImplementedError
        elif (db_engine == 'mysql'):
            create = executesql(('SHOW    CREATE    TABLE    `%s`;' % tablename))[0][1]
            fk = create.split(('`    FOREIGN    KEY    (`%s' % fieldname))[0].split('CONSTRAINT    `').pop()
            if ('`' in fk):
                fk = fk.split('`')[0]
            sql = ('ALTER    TABLE    `%(tablename)s`    DROP    FOREIGN    KEY    `%(fk)s`;' % dict(tablename=tablename, fk=fk))
        elif (db_engine == 'postgres'):
            sql = ('ALTER    TABLE    %(tablename)s    DROP    CONSTRAINT    %(tablename)s_%(fieldname)s_fkey;' % dict(tablename=tablename, fieldname=fieldname))
        try:
            executesql(sql)
        except:
            print ('Error:    Table    %s    with    FK    %s' % (tablename, fk))
            import sys
            e = sys.exc_info()[1]
            print >>sys.stderr, e
