I have a Django app named site_settings
in which SiteSettings
model is defined. This model contains a foreign key to django.contrib.sites.models.Site
model. Now I want to override default objects
manager of Site
model with new one I defined:
from django.contrib.sites.models import SiteManager as _OrigSiteManager
class SiteManager(_OrigSiteManager):
...
I tried:
Site.add_to_class("objects", SiteManager())
But it didn't work. The problem is I am adding to class with already existing objects
name. When adding with another name, it works as expected:
Site.add_to_class("my_objects", SiteManager()) # now Site.my_objects points to my custom manager
But I want to override existing objects
manager with my custom manager. How can I do that?
You can redefine and use your own Site class everywhere:
from django.contrib.sites.models import Site
class Site(Site):
...
objects = SiteManager()
or you can use contribute_to_class
:
from django.contrib.sites.models import Site
SiteManager().contribute_to_class(Site, 'objects')
or you can made monkey patch:
from django.contrib.sites.models import Site
Site.objects = SiteManager(model=Site)
If you need it only to change queryset in foreignkey to Site, you can use limit_choices_to
:
foreignkey(Site, limit_choices_to=Q(your query to limit sites queryset))