如何从现场添加经理
我想要做的是,当某些模型使用我的字段时,它会自动将自定义管理器添加到该模型。
据我所知,contibute_to_class提供了这样的功能
class MyCustomField(CharField):
def contribute_to_class(self, cls, name):
super(MyCustomField, self).contribute_to_class(cls, name)
setattr(cls, 'custom_manager', CustomManager())
问题是,在我的自定义管理器中,我使用 self.model._default_manager 对默认管理器进行查询,但是当我尝试这样做时,django 说 AttributeError: 'NoneType' object has no attribute '_default_manager'
如果我不使用contribute_to_class 并在我的模型类旁边编写自定义管理器,它会按预期工作。 可能是什么问题?
What i want to do is when some model use my field, it will automaticaly add custom manager to that model.
As far as i know, contibute_to_class provide such functionality
class MyCustomField(CharField):
def contribute_to_class(self, cls, name):
super(MyCustomField, self).contribute_to_class(cls, name)
setattr(cls, 'custom_manager', CustomManager())
The problem is that in my custom manager i use self.model._default_manager to do queries on default manager but when i try to do it, django says AttributeError: 'NoneType' object has no attribute '_default_manager'
If i dont use contribute_to_class and write custom manager iside my model class, it works as expected. What can be the problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
管理器,就像字段一样,有一个contribute_to_class方法,如果你不调用它,它们将无法正确设置。 正确的调用方法是使用 Model.add_to_class:
Managers, just like Fields, have a contribute_to_class method, and if you don't call it they won't be set up properly. The correct way to call it is by using Model.add_to_class: