问题描述:

Here is my problem. I am trying to add instrumentation to my code which is based off Django. Here is what I do:

def trace(func):

def wrapped(*args, **kwargs):

print func.__name__

return func(*args, **kwargs)

return wrapped

def trace_class_func(kclass, func):

setattr(kclass, func.__name__, classmethod(trace(func.im_func)))

# Trace all the calls to 'get_query_set' from all the classes or subclasses of Manager

tracer.trace_class_func(models.Manager, models.Manager.get_query_set)

This class is stored inside the module "tracer" and I add 'tracer' in the INSTALLED_APPS section of settings.py (note that the 'tracer' module' is added at the last).

However, when I run my app, I get this error:

Exception Type: AttributeError at /settings/integrations/

Exception Value: type object 'UserManager' has no attribute 'model'

This happens inside django/db/models/manager.py in get_query_set function.

EDIT: The deal is that when I tried to print the contents of UserManager class (which is derived from models.Manager), only the fields defined in UserManager were being recognized and none of the fields from the base class:

self: <class 'django.contrib.auth.models.UserManager'>

keys: {'__module__': 'django.contrib.auth.models', 'create_superuser': <function create_superuser at 0x10d44eaa0>, 'create_user': <function create_user at 0x10d44ea28>, 'make_random_password': <function make_random_password at 0x10d44eb18>, '__doc__': None, '__init__': <function __init__ at 0x10d44e9b0>}

As it can be seen, even the functions defined by UserManager are only being printed, not the ones defined by models.Manager. Not sure why this is happening, though.

Does anybody have an idea what is going on here? Because when I run this tracer on my custom made classes (including base and inherited classes), it works perfectly, so I am guessing this is a Django error, either in my configuration or something else.

网友答案:

The problem is that get_query_set isn't a class method. The instance itself is ignored and thus self != instance, it's the class which doesn't have a model.

A class method receives the class itself as the first argument, not the instance.

class MyClass(object):
   @classmethod
   def foo(cls):
       print "i'm a class: {0}".format(cls)
# i'm a class: __main__.MyClass

class MyClass(object):
   def foo(self):
       print "i'm a class instance: {0}".format(self)
# i'm a class instance: <__main__.MyClass instance at 0x1064abef0>
相关阅读:
Top