尝试将装饰器添加到models.Manager时出现Python Django错误

时间:2012-01-22 19:06:40

标签: python django inheritance models decorator

这是我的问题。我正在尝试将检测添加到基于Django的代码中。这是我的工作:

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)

这个类存储在模块“tracer”中,我在settings.py的INSTALLED_APPS部分添加'tracer'(注意最后添加'tracer'模块'。)

然而,当我运行我的应用程序时,我收到此错误:

异常类型:/ settings / integrations /中的AttributeError 异常值:类型对象'UserManager'没有属性'model'

这发生在get_query_set函数中的django / db / models / manager.py中。

编辑:当我尝试打印UserManager类的内容(来自models.Manager)时,只有UserManager中定义的字段被识别,并且基类中没有字段:

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>}

可以看出,即使是UserManager定义的功能也只是打印,而不是由models.Manager定义的功能。但不确定为什么会这样。

有人知道这里发生了什么吗?因为当我在自定义类(包括基类和继承类)上运行此跟踪器时,它运行完美,所以我猜这是一个Django错误,无论是在我的配置还是其他方面。

1 个答案:

答案 0 :(得分:0)

问题是get_query_set不是类方法。实例本身被忽略,因此self!= instance,它是没有模型的类。

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>
相关问题