Hi there, I’m trying to set my custom manager dynamically for given models.
Here is a sample of my code
class CustomManager(models.Manager):
def active(self):
return self.filter(name__startswith='c')
def set_custom_manager(model_class, manager=CustomManager(), manager_name='objects'):
setattr(model_class, manager_name, manager)
return model_class
class Facility(BaseModel):
name = models.CharField(_("Name"), max_length=255)
icon = models.ImageField(upload_to='location/facilities/')
order = models.PositiveIntegerField(_("Order"), default=0)
class Meta:
verbose_name = _("Facility")
verbose_name_plural = _("Facilities")
ordering = ['order', 'id']
def __str__(self):
return self.name
set_custom_manager(Facility, CustomManager())
If I check manager class name of Facility instance, it’s returning true
>>> Facility.objects.__class__
<class 'apps.chargers.models.CustomManager'>
But if I try to use default methods of models.Manager, it’s returning error
Facility.objects.all()
Traceback (most recent call last):
File "/opt/homebrew/Cellar/python@3.10/3.10.14/Frameworks/Python.framework/Versions/3.10/lib/python3.10/code.py", line 90, in runcode
exec(code, self.locals)
File "<console>", line 1, in <module>
File "/Users/njr/PycharmProjects/iwatt-backend/venv/lib/python3.10/site-packages/django/db/models/query.py", line 376, in __repr__
data = list(self[: REPR_OUTPUT_SIZE + 1])
File "/Users/njr/PycharmProjects/iwatt-backend/venv/lib/python3.10/site-packages/django/db/models/query.py", line 400, in __iter__
self._fetch_all()
File "/Users/njr/PycharmProjects/iwatt-backend/venv/lib/python3.10/site-packages/django/db/models/query.py", line 1928, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "/Users/njr/PycharmProjects/iwatt-backend/venv/lib/python3.10/site-packages/django/db/models/query.py", line 99, in __iter__
model_cls = klass_info["model"]
TypeError: 'NoneType' object is not subscriptable