需要一种方法来调用User.objects.filter/get
仅返回is_active
设置为 True 的用户对象。
我尝试定义一个自定义 Manager 并将其修补到 User 模型上,如下所示:
class CustomUserManager(UserManager):
def get_query_set(self):
return super(CustomUserManager, self).get_query_set().
filter(is_active=True)
User.objects = CustomUserManager()
User.objects_all = UserManager()
但是,当我尝试调用 User.objects.get() 时,我得到:
AttributeError: 'NoneType' object has no attribute '_meta'
在我进一步讨论之前,我想说我知道像这样的猴子补丁在可维护性方面是非常糟糕的形式——这将被标记为稍后重新访问,但现在我们需要一个快速的解决方案。
这是完整的堆栈跟踪,如果有人也想要的话:
File "<console>", line 1, in <module>
File "/Users/zarathustra/Virtual_Envs/fierce-spring-7383/venv/lib/python2.7/site-packages/django/db/models/manager.py", line 131, in get
return self.get_query_set().get(*args, **kwargs)
File "/Users/zarathustra/Virtual_Envs/fierce-spring-7383/venv/lib/python2.7/site-packages/django/db/models/query.py", line 358, in get
clone = self.filter(*args, **kwargs)
File "/Users/zarathustra/Virtual_Envs/fierce-spring-7383/venv/lib/python2.7/site-packages/django/db/models/query.py", line 621, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/Users/zarathustra/Virtual_Envs/fierce-spring-7383/venv/lib/python2.7/site-packages/django/db/models/query.py", line 639, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/Users/zarathustra/Virtual_Envs/fierce-spring-7383/venv/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1250, in add_q
can_reuse=used_aliases, force_having=force_having)
File "/Users/zarathustra/Virtual_Envs/fierce-spring-7383/venv/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1114, in add_filter
opts = self.get_meta()
File "/Users/zarathustra/Virtual_Envs/fierce-spring-7383/venv/lib/python2.7/site-packages/django/db/models/sql/query.py", line 233, in get_meta
return self.model._meta
AttributeError: 'NoneType' object has no attribute '_meta'