How to add a Manager from Field

狂风中的少年 提交于 2019-12-21 21:10:14

问题


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?


回答1:


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())



回答2:


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)


来源:https://stackoverflow.com/questions/609563/how-to-add-a-manager-from-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!