如何从现场添加经理

发布于 2024-07-14 22:01:51 字数 541 浏览 9 评论 0原文

我想要做的是,当某些模型使用我的字段时,它会自动将自定义管理器添加到该模型。

据我所知,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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

甜点 2024-07-21 22:01:51

管理器,就像字段一样,有一个contribute_to_class方法,如果你不调用它,它们将无法正确设置。 正确的调用方法是使用 Model.add_to_class:

class MyCustomField(CharField):
    def contribute_to_class(self, cls, name):
        super(MyCustomField, self).contribute_to_class(cls, name)
        cls.add_to_class('custom_manager', CustomManager())

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:

class MyCustomField(CharField):
    def contribute_to_class(self, cls, name):
        super(MyCustomField, self).contribute_to_class(cls, name)
        cls.add_to_class('custom_manager', CustomManager())
因为看清所以看轻 2024-07-21 22:01:51
class MyCustomField(CharField):
    def contribute_to_class(self, cls, name):
        super(MyCustomField, self).contribute_to_class(cls, name)
        manager = CustomManager()
        manager.model = cls
        setattr(cls, 'custom_manager', manager)
class MyCustomField(CharField):
    def contribute_to_class(self, cls, name):
        super(MyCustomField, self).contribute_to_class(cls, name)
        manager = CustomManager()
        manager.model = cls
        setattr(cls, 'custom_manager', manager)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文