'Set the application_name on PostgreSQL connection
Use the fallback_application_name to let the user override
it with PGAPPNAME env variable
http://www.postgresql.org/docs/9.4/static/libpq-connect.html#LIBPQ-PARAMKEYWORDS  # noqa'

def set_application_name(self, options):

    supported_backends = ['django.db.backends.postgresql', 'django.db.backends.postgresql_psycopg2']
    opt_name = 'fallback_application_name'
    default_app_name = 'django_shell'
    app_name = default_app_name
    dbs = getattr(settings, 'DATABASES', [])
    for db in dbs.keys():
        if (dbs[db]['ENGINE'] in supported_backends):
            try:
                options = dbs[db]['OPTIONS']
            except KeyError:
                options = {}
            if (opt_name in options.keys()):
                app_name = dbs[db]['OPTIONS'][opt_name]
            else:
                dbs[db].setdefault('OPTIONS', {}).update({opt_name: default_app_name})
                app_name = default_app_name
    return app_name
