Search code examples
pythondjangodjango-modelsmodels

get call stack for Model Classes in Django


In Django, I would like to get call stacks of classes in Model; on call, and log them. The Django Model uses QuerySet API to access objects of the Model class.

Say, we have defined Model class Abc, and it is called by other django apps using QuerySet API.

For example -

Abc.objects.filter()

Abc.objects.get()

,etc.

I would like to add a traceback whenever that particular Model class Abc is called via QuerySetAPI .

Is traceback a correct approach here? Should I use something else?

I am using Python 2.7, Vegrant, Django 1.4.20 on Mac.


Solution

  • If I understood you right, this is my solution. Any call to queryset api prints caller stack.

    import inspect
    from django.db import models
    from django.db.models import Manager
    
    class LogManager(Manager):
        def get_queryset(self):
            print inspect.stack()  # in py3.4 the [2] element was the actual caller outside Manager so I used [2:]
            return super(LogManager, self).get_queryset()
    
    class Abc(models.Model):
        objects = LogManager()
    

    UPD.: For all django versions < 1.5 you should override get_query_set:

    class LogManager(Manager):
        def get_query_set(self):
            print inspect.stack()
            return super(LogManager, self).get_query_set()