'Modify the ondelete constraint for a foreign key'

def ondelete(self, tablename, fieldname, reftable, ondelete):

    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`,    ALTER    TABLE    %(tablename)s    ADD    CONSTRAINT    %(fk)s    FOREIGN    KEY    (%(fieldname)s)    REFERENCES    %(reftable)s(id)    ON    DELETE    %(ondelete)s;' % dict(tablename=tablename, fk=fk, fieldname=fieldname, reftable=reftable, ondelete=ondelete))
            try:
                executesql(sql)
            except:
                print ('Error:    Cannot    amend    ondelete    for    Table    %s    and    Field    %s' % (tablename, fieldname))
                import sys
                e = sys.exc_info()[1]
                print >>sys.stderr, e
        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:    Cannot    remove    old    ondelete    for    Table    %s    and    Field    %s' % (tablename, fieldname))
                import sys
                e = sys.exc_info()[1]
                print >>sys.stderr, e
            sql = ('ALTER    TABLE    %(tablename)s    ADD    CONSTRAINT    %(tablename)s_%(fieldname)s_fkey    FOREIGN    KEY    (%(fieldname)s)    REFERENCES    %(reftable)s(id)    ON    DELETE    %(ondelete)s;' % dict(tablename=tablename, fieldname=fieldname, reftable=reftable, ondelete=ondelete))
            try:
                executesql(sql)
            except:
                print ('Error:    Cannot    add    new    ondelete    for    Table    %s    and    Field    %s' % (tablename, fieldname))
                import sys
                e = sys.exc_info()[1]
                print >>sys.stderr, e
        else:
            raise NotImplementedError
