Django - How to override a filter on a model?

I am curious if there is a best practice or recommended way to do this?

Say I have a model like this:

class Cat(models.Model):
    field1=models.CharField(...)
    field2=models.CharField(...)
    evil=models.BooleanField(...)

What I'm trying to accomplish is that I don't want any views to ever have access to Cat records where evil is true.

Do I really need to add .filter (evil = False) to every Cat.objects.filter call, or is there a way to do this once in the class and make the evil cats never appear anywhere?

+5
source share
1 answer

Well, a user manager can fit here. Just look through the docs . And, as Chris Pratt said, keep in mind that the first manager is becoming standard.

We hope that this will lead to the right direction.

Update (maybe you could do this):

from django.db import models

class EvilCategoryManager(models.Manager):
    def get_query_set(self):
        return super(EvilCategoryManager, self).get_query_set().filter(evil=False)

class Cat(models.Model):
    #.... atrributes here
    objects = models.Manager()
    no_evil_cats = EvilCategoryManager()
+8
source

All Articles