Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - How to override filter on a model?

I'm curious if there's a best practice, or recommended way to accomplish 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 I want no views to ever be able to access Cat records where evil is True.

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

like image 918
Greg Avatar asked Jul 23 '12 17:07

Greg


1 Answers

Ok, a custom manager could fit in here. Just have a look into the docs. And like Chris Pratt said, keep in mind that the first manager becomes the default one.

Hope this leads into the right direction.

Update (maybe you could do it like 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()
like image 54
Jingo Avatar answered Sep 30 '22 14:09

Jingo