Defining custom RelatedManager in django

1.9k Views Asked by At

I want to override related manager for a class.

I have a Company model. It has state column which can be in ACTIVE, INACTIVE, SUSPENDED. I am adding 2 new states called SALES, CLOSED.

Since its legacy model, just adding state can be devastating(there are very many places in code which doesn't filter by state).

So, to avoid inadvertent changes elsewhere, I decided to hide our new states for all other apps/elsewhere unless required otherwise (I'll whitelist only for our app/models)

I've overridden object manager in company.

class CompanyManager(models.Manager):

    def get_queryset(self):
        return super(CompanyRelatedManager, self).get_queryset().exclude(state__in=['SALES', 'CLOSED'])

class Company(models.Model):
    _default_manager = models.Manager()
    objects = CompanyManager()
    allObjects = models.Manager()

    name = models.TextField()
    ...
    salesContact = models.ForeignKey(Contact)

The problem is that Company.objects.filter(blah=blah) filters out new states. But something like salesContact.companies.all() doesn't.

In [9]: salesContact.companies
Out[9]: <django.db.models.fields.related.RelatedManager at 0x12157a990>

My question is how to override the related manager of the salesContact = models.ForeignKey(Contact) and the likes so that I can modify the default queryset to exclude my new state.

And, I can't override the default manager, since overriding default manager also implies that I am overriding the db_manager which results in un-intended consequence (db tries to insert instead of update, whole other story).

0

There are 0 best solutions below