0

I need to set variable in db scope what will containt django user id what making DML query. something like this :

CREATE OR REPLACE FUNCTION set_user_id(auser_id integer)
  RETURNS void AS
  'GD["user_id"] = auser_id'
  LANGUAGE plpythonu VOLATILE
  COST 100;

and call this function before every DML to pass that user id into audit trigger; Is there is an easy way to do it?

Andrey Baryshnikov
  • 781
  • 2
  • 12
  • 22
  • 1
    Before EVERY insert/update/delete? I dont know. But for your models you can create signals https://docs.djangoproject.com/en/dev/topics/signals/ perhaps that could help? – dm03514 May 03 '12 at 12:17
  • Yes, before every DML;I think i can handle it in middleware, and set user id if request methonds are post/delete/put – Andrey Baryshnikov May 03 '12 at 12:24

1 Answers1

0

If you need this to be done only for certain models, then you should override the save method of the model.

If you need this to be done irrespective of the models being using but across any model that accesses your particular database, then you should create your own variant of the db backend by adapting one for your particular database (in this case, I suspect its postgresql).

Something like this should do it:

from django.db.backends.postgresql_psycopg2.base import *

class DatabaseWrapper(DatabaseWrapper):
    def _cursor(self):
        cursor = super(DatabaseWrapper, self)._cursor()
        q = " ... enter your query here ..."
        cursor.execute(q % (arg1,arg2))
        return cursor
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
  • Thank you for answer, Burhan Khalid. But in this case how can i get any information about user what performing DML request ? I need request object to do this. I can do it in middleware. but in this case, i need connection-safe variable, in my case GD from plpython - bad idea. but django closes db-connection after request , that istablished it, finish. – Andrey Baryshnikov May 03 '12 at 19:58